因此,我正在研究regexp,以捕获字符串中的所有链接,意思是以http、https等协议开头的单词,以www开头的单词。或者以特定领域".com“、".hr”和".net“结尾的单词。但不知怎么的,我做的这个regexp总是返回以协议开头的所有链接,但只返回最后一个以特定域结束的链接。我做错什么了?非常感谢!
$description='test.com test2.hr http://www.test3.hr https://test4.com test3.net';
$pattern = '/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&@#\/%=~_|$?!:,.]*[A-Z0-9+&@#\/%=~_|$]|(?:\b((?:[\w]+\.com$)|(?:[\w]+\.hr$)|(?:[\w]+\.net$)))/i';
preg_match_all($pattern, $description, $out);
var_dump($out[0]);发布于 2015-04-28 13:52:58
您的原始正则表达式有一些问题。首先,您应该使用条件修饰符?来处理协议。我不知道为什么要使用第二个[A-Z0-9+&@#\/%=~_|$]块,也不知道为什么在之后使用|操作符;如果有特定的原因,请告诉我。最后,$只在正则表达式的末尾使用它时才起作用;否则,您应该使用\Z,它在正则表达式中的任何一点上都与字符串结束匹配,尽管我不认为您希望在这里匹配字符串的结束。我已经按照你想要的方式重写了下面的正则表达式:
$description='test.com test2.hr http://www.test3.hr https://test4.com test3.net trash string don\'t match test4.net';
$pattern = '/(?:(?:https?|ftp|file):\/\/(?:www|ftp)\.)?[-A-Z0-9+&@#\/%=~_|$?!:,.]*(\.[A-Z]+)/i';
preg_match_all($pattern, $description, $out);
var_dump($out[0]);返回:
array(6) {
[0]=>
string(8) "test.com"
[1]=>
string(8) "test2.hr"
[2]=>
string(19) "http://www.test3.hr"
[3]=>
string(17) "https://test4.com"
[4]=>
string(9) "test3.net"
[5]=>
string(9) "test4.net"
}https://stackoverflow.com/questions/29921185
复制相似问题