我们如何使用PHP来识别字符串中的URL并将其存储在数组中?
如果URL包含逗号,则无法使用explode
函数,因为它不会给出正确的结果。
REGEX是您的问题的答案。获取对象操纵器的答案。。它所缺少的只是排除"逗号",所以你可以尝试这个代码,它排除了它们,并给出了3个单独的URL作为输出:
$string = "The text you want to filter goes here. http://google.com, https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/";
preg_match_all('#'bhttps?://[^,'s()<>]+(?:'(['w'd]+')|([^,[:punct:]'s]|/))#', $string, $match);
echo "<pre>";
print_r($match[0]);
echo "</pre>";
输出为
Array
(
[0] => http://google.com
[1] => https://www.youtube.com/watch?v=K_m7NEDMrV0
[2] => https://instagram.com/hellow/
)
请尝试使用以下regex
$regex = '/https?':'/'/[^'",]+/i';
preg_match_all($regex, $string, $matches);
echo "<pre>";
print_r($matches[0]);
希望这将为您工作
您可以在此处尝试Regex:
$string = "The text you want to filter goes here. http://google.com, https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/";
preg_match_all('#'bhttps?://[^'s()<>]+(?:'(['w'd]+')|([^[:punct:]'s]|/))#', $string, $match);
echo "<pre>";
print_r($match[0]);
echo "</pre>";
这会产生以下输出:
Array
(
[0] => http://google.com
[1] => https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/
)
尝试这个
function getUrls($string)
{
$regex = '/https?':'/'/[^'" ]+/i';
preg_match_all($regex, $string, $matches);
return ($matches[0]);
}
$urls = getUrls($string);
print_r($urls);
或
$str = '<a href="http://foobar.com"> | Hello world Im a http://google.fr | Did you mean:http://google.fr/index.php?id=1&b=6#2310';
$pattern = '`.*?((http|ftp)://['w#$&+,'/:;=?@.-]+)[^'w#$&+,'/:;=?@.-]*?`i';
if (preg_match_all($pattern,$str,$matches))
{
print_r($matches[1]);
}
它将工作
$urlstring = "The text you want to filter goes here. http://google.com, https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/";
preg_match_all('#'bhttps?://[^,'s()<>]+(?:'(['w'd]+')|([^,[:punct:]'s]|/))#', $urlstring , $result);
print_r($result[0]);
$string = "The text you want to filter goes here. http://google.com,
https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/";
preg_match_all('#'bhttps?://[^'s()<>]+(?:'(['w'd]+')|([^[:punct:]'s]|/))#',
$string, $match);
echo "<pre>"; $arr = explode(",", $match[0][1]);
print_r($match[0][0]); print_r($arr); echo "</pre>";