我们如何使用PHP识别字符串中的URL并将它们存储在数组中?
如果网址包含逗号,则无法使用explode
函数,它不会给出正确的结果。
答案 0 :(得分:71)
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/
)
答案 1 :(得分:5)
请尝试使用以下正则表达式
$regex = '/https?\:\/\/[^\",]+/i';
preg_match_all($regex, $string, $matches);
echo "<pre>";
print_r($matches[0]);
希望这对你有用
答案 2 :(得分:4)
您可以在此处试用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/
)
答案 3 :(得分:3)
$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]);
答案 4 :(得分:2)
试试这个
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]);
}
它会起作用
答案 5 :(得分:2)
$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>";