Dylan Taylor
Dylan Taylor

Reputation: 71

PHP if string contains URL isolate it

In PHP, I need to be able to figure out if a string contains a URL. If there is a URL, I need to isolate it as another separate string.

For example: "SESAC showin the Love! http://twitpic.com/1uk7fi"

I need to be able to isolate the URL in that string into a new string. At the same time the URL needs to be kept intact in the original string. Follow?

I know this is probably really simple but it's killing me.

Upvotes: 1

Views: 6322

Answers (4)

Jazzy
Jazzy

Reputation: 6139

this doesn't account for dashes -. needed to add -

preg_match('/[a-zA-Z]+:\/\/[0-9a-zA-Z;.\/\-?:@=_#&%~,+$]+/', $_POST['string'], $matches);

Upvotes: 2

kzh
kzh

Reputation: 29

$test = "SESAC showin the Love! http://twitpic.com/1uk7fi";
$myURL= strstr ($test, "http");
echo $myURL; // prints http://twitpic.com/1uk7fi

Upvotes: -1

Artefacto
Artefacto

Reputation: 97835

Something like

preg_match('/[a-zA-Z]+:\/\/[0-9a-zA-Z;.\/?:@=_#&%~,+$]+/', $string, $matches);

$matches[0] will hold the result.

(Note: this regex is certainly not RFC compliant; it may fetch malformed (per the spec) URLs. See http://www.faqs.org/rfcs/rfc1738.html).

Upvotes: 9

Tomalak
Tomalak

Reputation: 338228

URLs can't contain spaces, so...

\b(?:https?|ftp)://\S+

Should match any URL-like thing in a string.

The above is the pure regex. PHP preg_* and string escaping rules apply before you can use it.

Upvotes: 0

Related Questions