Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP hiding multiple phone numbers

I am trying to replace phone numbers with [hidden] and show them back on click. It works great when there is only one number. But when there are more, it hides it, but the problem is that it 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??

Pretty much, if you can help me get the sizeOf($phone_matches) to show the correct amount, I should be good 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;
like image 843
BragDeal Avatar asked Sep 22 '14 20:09

BragDeal


1 Answers

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 iterate through all the matches you would do:

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

But for what you're actually trying to accomplish, there's no need for preg_match_all at all. A simple one-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);
like image 180
AlliterativeAlice Avatar answered Oct 16 '22 21:10

AlliterativeAlice