Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_match get numbers between two strings

Hi I'm starting to learn php regex and have the following problem: I need to extract the numbers inside $string. The regex I use returns "NULL".

$string = 'Clasificación</a> (2194)  </li>';
$regex = '/Clasificación</a>((.*?))</li>/';
preg_match($regex , $string, $match);
var_dump($match);

Thanks in advance.

like image 746
sms Avatar asked Dec 25 '22 15:12

sms


1 Answers

There are three problems with your regex:

  • You aren't escaping the forward slash. You're using the forward slash as a delimiter, so if you want to use it as a literal character inside the expression, you need to escape it
  • ((.*?)) doesn't do what you think it does. It creates two capturing groups -- one nested inside the other. I assume, you're trying to capture what's inside the parentheses. For that, you'll need to escape the ( and ) characters. The expression would become: \((.*?)\)
  • Your expression doesn't handle whitespace. In the string you've given, there is whitespace between the </a> and the beginning of the number -- </a> (2194). To ignore the whitespace and capture just the number, you need to use \s (which matches any whitespace character). For that, you need to write \s*\((.*?)\)\s*.

The final regular expression after fixing all the above errors, will look like:

$regex = '~Clasificación</a>\s*\((.*?)\)\s*</li>~';

Full code:

$string = 'Clasificación</a> (2194)  </li>';
$regex = '~Clasificación</a>\s*\((.*?)\)\s*</li>~';
preg_match($regex , $string, $match);
var_dump($match);

Output:

array(2) {
  [0]=>
  string(32) "Clasificación (2194)  "
  [1]=>
  string(4) "2194"
}

Demo.

like image 52
Amal Murali Avatar answered Dec 28 '22 08:12

Amal Murali