Extract URLs from text in PHP

后端 未结 14 2209
野趣味
野趣味 2020-11-22 13:29

I have this text:

$string = \"this is my friend\'s website http://example.com I think it is coll\";

How can I extract the link into another

14条回答
  •  遥遥无期
    2020-11-22 13:56

    The code that worked for me (especially if you have several links in your $string) is:

    $string = "this is my friend's website https://www.example.com I think it is cool, but this one is cooler https://www.stackoverflow.com :)";
    $regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i';
    preg_match_all($regex, $string, $matches);
    $urls = $matches[0];
    // go over all links
    foreach($urls as $url) 
    {
        echo $url.'
    '; }

    Hope that helps others as well.

提交回复
热议问题