There is such data:

$pattern = "/статьи/администрирование/([0-9])+/([0-9])+/"; $string = "/статьи/администрирование/129/123/"; 

I need some kind of mechanism that could extract the numbers 129 and 123 from $string , with what $pattern can change, for example, if it will be like this:

  $pattern = "/статьи/администрирование/([0-9])+/"; 

and $string is:

  $string = "/статьи/администрирование/129/"; 

then you need to pull out the number 129.

I did this:

 if(preg_match("~$pattern ~", $string ,$matches)){ echo "<pre>"; print_r($matches); echo "</pre>"; } 

But received in the $matches array is not what you need, namely:

 Array ( [0] => /статьи/администрирование/129/123/ [1] => 9 [2] => 3 ) 

How to make it so in the array:

Array ([0] => / articles / administration / 129/123 / [1] => 129 [2] => 123)

  • + inside the parentheses make - teran
  • ^ and remove the space before the tilde. and it will work - splash58
  • replace ([0-9])+ with (\d+) and remove the space after the template variable in "~$pattern ~" - Lexx918
  • Thank you all)) Write in the answers, mark as correct - Alexey Vladimirovich

1 answer 1

In addition to comments in the comments, you need to replace the delimiters in the template (so as not to screen slashes)

 $string = '/статьи/администрирование/129/123/'; $pattern = '~/статьи/администрирование/(\d+)/(\d+)/~'; preg_match($pattern, $string, $arr); var_dump($arr); 
  • This regular program will work fine without the u sandbox.onlinephpfunctions.com/code/… flag, since it does not have character classes with multibyte characters, and the substring /статьи/администрирование/ is uniquely defined in the same encoding;) - Visman
  • @Visman is really - now I will correct the answer. - Edward