如何使用PHP来识别字符串中的URL并将其存储到数组中?
如果URL包含逗号,则无法使用explode
函数获得正确结果。
正则表达式是解决你问题的答案。参照对象操作器的答案......唯一需要排除的是“逗号”,所以你可以尝试使用这段代码,它将排除它们并将给出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/
)
...#i'
。 - MrWhite$regex = '/https?\:\/\/[^\",]+/i';
preg_match_all($regex, $string, $matches);
echo "<pre>";
print_r($matches[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>";
print_r($match[0]);
echo "</pre>";
Array
(
[0] => http://google.com
[1] => https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/
)
http://google.com
、https://www.youtube.com/watch?v=K_m7NEDMrV0
和 https://instagram.com/hellow/
。 - Azraar Azwardfunction 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]);
}
它将会起作用。
Array([0] => http://google.com,[1] => https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/)
- Azraar Azward$string =“您要过滤的文本在此处。http://google.com,https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/”;
- Azraar Azward$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>";
preg_match_all("/\b((https?):\/\/)?([a-z0-9-.]*)\.([a-z]{2,3})([-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$])/i", $string, $match);
- Harsh Patel