PHP hides multiple phone numbers

I am trying to replace phone numbers with [hidden] and show them on click. It works great when there is only one number. But when there are more, he hides it, but the problem is that he returns the same number for both hidden fields.

$check ='111 111 1111 / 222 222 2222'; preg_match('/[(]*\d{3}[)]*\s*[.\- ]*\d{3}[.\- ]*\d{4}/', $check, $phone_matches); echo sizeOf($phone_matches); //returns 1, why not 2?? 

To a large extent, if you can help me get sizeOf($phone_matches) to show the correct amount, I should be fine from there!

EDIT:

 for($i=0; $i<sizeOf($phone_matches[0]); $i++){ $check = preg_replace('/[(]*\d{3}[)]*\s*[.\- ]*\d{3}[.\- ]*\d{4}/', '<span class="hide">'.$phone_matches[0][$i].'</span><span class="show">show phone</span>', $check); } echo $check; 
+5
source share
1 answer

You want to use preg_match_all , not preg_match

 preg_match_all('/[(]*\d{3}[)]*\s*[.\- ]*\d{3}[.\- ]*\d{4}/', $check, $phone_matches); print_r($phone_matches); 

But note that sizeof($phone_matches) will still be 1, since the array of matches is actually $phone_matches[0] .

To repeat all the matches you make:

 foreach ($phone_matches[0] as $match) { //Do something with $match } 

But for what you are actually trying to execute, there is no need for preg_match_all at all. A simple single line preg_replace will do the trick:

 $check = preg_replace('/[(]*\d{3}[)]*\s*[.\- ]*\d{3}[.\- ]*\d{4}/', '<span class="hide">$0</span><span class="show">show phone</span>', $check); 
+5
source

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


All Articles