Extract URLs from text in PHP

后端 未结 14 2089
野趣味
野趣味 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:48

    Probably the safest way is using code snippets from WordPress. Download the latest one (currently 3.1.1) and see wp-includes/formatting.php. There's a function named make_clickable which has plain text for param and returns formatted string. You can grab codes for extracting URLs. It's pretty complex though.

    This one line regex might be helpful.

    preg_match_all('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $string, $match);
    

    But this regex still can't remove some malformed URLs (ex. http://google:ha.ckers.org ).

    See also: How to mimic StackOverflow Auto-Link Behavior

提交回复
热议问题