Welcome Guest, Not a member yet? Register   Sign In
Finding URL & Email text in a string?

I've always been absolutely terrible with regex, it's just not my thing! Sad

Would anyone be able to give us a hand finding out if a string contains a url or email

[email protected]

How difficult would something like this be?

Do you need to extract an email and/or URL from a string, or check if a string is valid email/url?

If latter, it's easy:

filter_var($string, FILTER_VALIDATE_EMAIL);
filter_var($string, FILTER_VALIDATE_URL);

If former, it's a bit trickier. You can either try with regex, which I suggest you google for, or you can tokenize the string and check each token, like so:

foreach (preg_split('/\b/', $string) as $token) {
if (filter_var($token, FILTER_VALIDATE_EMAIL)) return $token;

\b in regex is word boundry (space, comma, dot, semicolon, etc.).

It's not going to just be an email or url, I want to know if it contains either as I don't want users to be able to contain either in posts they submit!

Are there no regex wizards that can help me? Sad

Why not use the second solution I provided? E.g. this piece of code:

foreach (preg_split(’/\b/’, $string) as $token) {
if (filter_var($token, FILTER_VALIDATE_EMAIL)) return $token;

use preg_match_all() to get the matches.

Theme © iAndrew 2016 - Forum software by © MyBB