Search code examples
phpregexpreg-match

Check if text contains url, email and phone number with php and regex


I have a text, for example, like:
$descrizione = "Tel.+39.1234.567899 [email protected] www.testwebsite.com"
and I would like to obtain three different variable with:
"+39.1234.567899"
"[email protected]"
"www.testwebsite.com
".
To check if text contains email I use regex and I write this code:

$regex = '/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})/';
if (preg_match($regex, $descrizione, $email_is)) {
     for($e = 0; $e < count($email_is) ; $e++){
          if(strpos($email_is[$e], "@") !== false){
               $linkEmail = $email_is[$e];
          }
     }
} 

now, I would like to find website url, so I try to write:

$regex = '/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi';
if( preg_match($regex, $descrizione, $matches)){
     $linkWebsite = $matches[0];
}

but the preg_match return false. I control the regex with the website http://regexr.com/ and it's correct, so I don't understand why return always false. Where is the problem?
I try to use "/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/" but I have the same problem and I try to check errors with trycatch but it doesn't return errors.

Finally I would like to find phone number but I don't know how to write regex.
Is there someone thet can help me, please?


Solution

  • I have find the solution, I hope thet this can help someone.
    The preg_match returns only first result and not all the result thet it has find.
    So, if I check the regex using a website like regex101, it returns the corrects result with all matches, but if I use the same regex in php, it returns only one.
    The regex option "g" (global = don't return after first match) corresponds to the function preg_match_all.