1

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 everything that doesn't 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 everything except integer/floating numbers, etc...

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

0

Your regex needs to have $ and ^ removed in order to work, those symbols cannot be found in the middle of the string. If your regex matches it cannot possibly contain anything else but email.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.