shuba.ivan
shuba.ivan

Reputation: 4071

PHP Regular find url and email

I need to find "http" and "https" and "email" inside text. I have tried:

    $regex = "((https|ftp)\:\/\/)"; // http and https
    $regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)"; // email

    if(preg_match("/^$regex$/", $comment))
    {
        $r = 'find';
    } else {
        $r = 'not find';
    }

with the following text:

$comment = 'hello https:// and hello email [email protected]'

But it doesn't work. Probably because of wrong split.

I tried with filter like this:

    if (filter_var($comment, FILTER_VALIDATE_EMAIL)) {
        return new \Exception('exist url');
    }

but when I have only email in comment filter, it works and finds this email, if I have 'hello [email protected]', it does not find the email.

For filter FILTER_VALIDATE_URL - it won't find the url if it is like this 'hello erl https:\hello'

How to write the right regex to find url or email in some text?

Upvotes: 0

Views: 120

Answers (1)

C14L
C14L

Reputation: 12558

In this line

if(preg_match("/^$regex$/", $comment))

you have ^ then $regex and $. The ^ means to only match at the beginning of the line. The $ means to only match at the end. Therefor, this would only match if that line contained only the match and nothing else.

Remove it to get matches anywhere in a line.

if(preg_match("/$regex/", $comment))

However, I would suggest to simply look for a library that offers the matching you are looking for. A library will have much more testing done to cover edge cases and other things that are easily missed.

Upvotes: 2

Related Questions