开发者

Why preg_match fails to get the result?

I have the below开发者_开发技巧 text displayed on the browser and trying to get the URL from the string.

string 1 = voice-to-text from #switzerland: http://bit.ly/lnpDC12D

When I try to use preg_match and trying to get the URL, but it fails

$urlstr = "";
preg_match('/\b((?#protocol)https?|ftp):\/\/((?#domain)[-A-Z0-9.]+)((?#file)\/[-A-Z0-9+&@#\/%=~_|!:,.;]*)?((?#parameters)\?[A-Z0-9+&@#\/%

=~_|!:,.;]*)?/i', $urlstr, $match);

echo $match[0];

I think #switzerland: has one more http// ... will it be problem ?

the above split works perfect for the below string,

voice-to-text: http://bit.ly/jDcXrZg


In this case I think parse_url will be better choice than regex based code. Something like this may work (assuming your URL always starts with http):

$str = "voice-to-text from #switzerland: http://bit.ly/lnpDC12D";
$pos = strrpos($str, "http://");
if ($pos>=0) {
   var_dump(parse_url(substr($str, $pos)));
}

OUTPUT

array(3) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(6) "bit.ly"
  ["path"]=>
  string(9) "/lnpDC12D"
}


As far as I understand your request, here is a way to do it :

$str = 'voice-to-text from <a href="search.twitter.com/…;: http://bit.ly/lnpDC12D';
preg_match("~(bit.ly/\S+)~", $str, $m);
print_r($m);

output:

Array
(
    [0] => bit.ly/lnpDC12D
    [1] => bit.ly/lnpDC12D
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜