tags:

views:

202

answers:

2

Hi guys, i have some regexp (like ^\w+[\w-.]\@\w+((-\w+)|(\w)).[a-z]{2,3}$, to match correct emails), but i cant figure out how to remove everythings that dont match the regexp in my string.

Keeping the email example, i need a way to, given a sting like

$myString = "This is some text, the email is here [email protected], and other things over here";

i need to return just '[email protected]', or boolean false, if there is no email in the strings.

Of course, the email is just an example, some others times i'll need to remove everythings except integer/floating numbers, ecc...

I've googled around so much but didn't find anything..

+3  A: 

If you surround your regex in parentheses and use preg_match or preg_match_all it will only return the part of the string that was matched by the regular expression:

$myString = "This is some text, the email is here [email protected], and other things over here";
preg_match("/(\w+[\w-.]\@\w+((-\w+)|(\w)).[a-z]{2,3})/", $myString, $matches);
print_r($matches);

Note I also took off the beginning and end of string delimeters as in this case they are not needed.

Paolo Bergantino
+1  A: 

Use the preg_match_all function to match all occurrences. The preg_match_all function itself returns the number of matches or false if an error occured.

So:

$myString = "This is some text, the email is here [email protected], and other things over here";
if (($num = preg_match_all('/\w+[\w-.]\@\w+((-\w+)|(\w)).[a-z]{2,3}/', $myString, $matches)) !== false) {
    echo $num.' matches have been found.';
    var_dump($matches);
} else {
    // error
}
Gumbo