Find url from string with php

前端 未结 3 1678
野性不改
野性不改 2020-12-09 21:34

following code is used to find url from a string with php. Here is the code:

$string = \"Hello http://www.bytes.com world www.yahoo.com\";
preg_match(\'/(htt         


        
相关标签:
3条回答
  • 2020-12-09 21:55

    A working method for linking with http/https/ftp/ftps/scp/scps: $newStr = preg_replace('!(http|ftp|scp)(s)?:\/\/[a-zA-Z0-9.?&_/]+!', "<a href=\"\\0\">\\0</a>",$str);

    I strongly advise NOT linking when it only has a dot, because it will consider PHP 5.2, ASP.NET, etc. links, which is hardly acceptable.

    Update: if you want www. strings as well, take a look at this.

    0 讨论(0)
  • 2020-12-09 22:05

    If you want to detect something like stackoverflow.com, then you're going to have to check for all possible TLDs to rule out something like Web 2.0, which is quite a long list. Still, this is also going to match something as ASP.NET etc.

    The regex would looks something like this:

    $hypertext = preg_replace(
        '{\b(?:http://)?(www\.)?([^\s]+)(\.com|\.org|\.net)\b}mi',
        '<a href="http://$1$2$3">$1$2$3</a>',
        $text
    );
    

    This only matches domains ending in .com, .org and .net... as previously stated, you would have to extend this list to match all TLDs

    0 讨论(0)
  • 2020-12-09 22:05

    @axiomer your example wasn't work if link will be in format:

    https://stackoverflow.com?val1=bla&val2blablabla%20bla%20bla.bl

    correct solution:

    preg_replace('!(http|ftp|scp)(s)?:\/\/[a-zA-Z0-9.?%=&_/]+!', "<a href=\"\\0\">\\0</a>", $content);
    

    produces:

    <a href="https://stackoverflow.com?val1=bla&val2blablabla%20bla%20bla.bl">https://stackoverflow.com?val1=bla&val2blablabla%20bla%20bla.bl</a>
    
    0 讨论(0)
提交回复
热议问题