PHP if string contains URL isolate it

2019-01-29 06:20发布

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.

标签: php url string
4条回答
祖国的老花朵
2楼-- · 2019-01-29 06:58

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

preg_match('/[a-zA-Z]+:\/\/[0-9a-zA-Z;.\/\-?:@=_#&%~,+$]+/', $_POST['string'], $matches);
查看更多
Evening l夕情丶
3楼-- · 2019-01-29 07:05

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.

查看更多
Fickle 薄情
4楼-- · 2019-01-29 07:20

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).

查看更多
看我几分像从前
5楼-- · 2019-01-29 07:21
$test = "SESAC showin the Love! http://twitpic.com/1uk7fi";
$myURL= strstr ($test, "http");
echo $myURL; // prints http://twitpic.com/1uk7fi
查看更多
登录 后发表回答