Search code examples
phppreg-match

Do a Preg_match then check each option individually


Good Afternoon All,

I've been stuck this issue for days now and I've finally decided I need some help. Each time I do Pregmatch like this :

$regp = "/(\s*)(\s*\(?0\d{4}\)?(\s*|-)\d{3}(\s*|-)\d{3}\s*)|(\s*\(?0\d{3}\)?(\s*|-)\d{3}(\s*|-)\d{4}\s*)|(\s*(7|8)(\d{7}|\d{3}(\-|\s{1})\d{4})\s*)/";
preg_match_all($regp, $html[1], $phonematch, PREG_SET_ORDER, 0);  
foreach($phonematch as $resultp) {
    echo $resultp[0];  
    echo "</br>"; 
}  

I do get the results I need but what I now need to do is a if statement that checks each one to see if it contains a 0 at the front then if it does display the result if it doesn't don't display it, but no matter how many different ways I try I cannot seem to find a way to achieve this.

Thanks for your help all.


Solution

  • I would just add substr() in the loop or if you want skip it completely then just add 0 in the begining of your regex

    $regp = "/(\s*)(\s*\(?0\d{4}\)?(\s*|-)\d{3}(\s*|-)\d{3}\s*)|(\s*\(?0\d{3}\)?(\s*|-)\d{3}(\s*|-)\d{4}\s*)|(\s*(7|8)(\d{7}|\d{3}(\-|\s{1})\d{4})\s*)/";
    preg_match_all($regp, $html[1], $phonematch, PREG_SET_ORDER, 0);  
    
    foreach($phonematch as $resultp) {
        if (substr($resultp[0], 0, 1) !== '0') {
           continue;
        }
    
        echo $resultp[0];  
        echo "</br>"; 
    }