PHP preg_match returns only the first match

  1. The first question is:

I use http://www.phpliveregex.com/ to check the validity of my regular expression, and it finds more than one matching string.

I am doing this regex:

$lines = explode('\n', $text); foreach($lines as $line) { $matches = []; preg_match("/[0-9]+[AZ][az]+ [AZ][az]+S[0-9]+\-[0-9]+T[0-9]+/uim", $line, $matches); print_r($matches); } 

on $text that looks like this: http://pastebin.com/9UQ5wNRu

The problem is that printed matches are just one match:

 Array ( [0] => 3Bajus StanislavS2415079249-2615T01 ) 

Why is this doing to me? Any ideas what might solve the problem?

  1. Second question

Perhaps you noticed in the text not the usual alphabetic characters of the Slovak language (from pastebin). How to match these characters and select users who have this format:

 {number}{first_name}{space}{last_name}{id_number} 

how to do it?

Well, the first problem is fixed. Thanks @ chris85. I had to use preg_match_all and do this for the whole text. Now I get an array of all students whose names contain Slovak (English) letters.

+7
source share
2 answers

preg_match for one match. You must use preg_match_all for a global search.

[AZ] contains no characters outside this range. Since you are using the i modifier, that character class is [A-Za-z] , which may or may not be what you want. You can use \p{L} instead for characters from any language.

Demo: https://regex101.com/r/L5g3C9/1

So your PHP code is simple:

 preg_match_all("/^[0-9]+\p{L}+ \p{L}+S[0-9]+\-[0-9]+T[0-9]+$/uim", $text, $matches); print_r($matches); 
+7
source

You can also use the T-Regx library :

 pattern("^[0-9]+\p{L}+ \p{L}+S[0-9]+\-[0-9]+T[0-9]+$", 'uim')->match($text)->all(); 
0
source

Source: https://habr.com/ru/post/1261584/


All Articles