Extract URL's from a string using PHP [duplica

2019-01-22 02:23发布

This question already has an answer here:

How can we use PHP to identify URL's in a string and store them in an array?

Cannot use the explode function if the URL contains a comma, it wont give correct results.

标签: php url
6条回答
对你真心纯属浪费
2楼-- · 2019-01-22 03:00

REGEX is the answer for your problem. Taking the Answer of Object Manipulator.. all it's missing is to exclude "commas", so you can try this code that excludes them and gives 3 separated URL's as output:

$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>";

and the output is

Array
(
    [0] => http://google.com
    [1] => https://www.youtube.com/watch?v=K_m7NEDMrV0
    [2] => https://instagram.com/hellow/
)
查看更多
Root(大扎)
3楼-- · 2019-01-22 03:00

You can try Regex here:

$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>";

This gives the following output:

Array
(
  [0] => http://google.com
  [1] => https://www.youtube.com/watch?v=K_m7NEDMrV0,https://instagram.com/hellow/
)
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-22 03:10

try this

function getUrls($string)
{
$regex = '/https?\:\/\/[^\" ]+/i';
preg_match_all($regex, $string, $matches);
return ($matches[0]);
}
$urls = getUrls($string);
print_r($urls);

or

$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]);
}

it will works

查看更多
Summer. ? 凉城
5楼-- · 2019-01-22 03:11
$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>";
查看更多
迷人小祖宗
6楼-- · 2019-01-22 03:11
$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]); 
查看更多
男人必须洒脱
7楼-- · 2019-01-22 03:13

please try to use below regex

$regex = '/https?\:\/\/[^\",]+/i';
preg_match_all($regex, $string, $matches);
echo "<pre>";
print_r($matches[0]); 

Hope this will work for you

查看更多
登录 后发表回答