PHP:如何从字符串中获取Web地址并创建没有查询字符串的链接?

时间:2017-10-03 14:11:11

标签: php regex hyperlink

我将这些随机概要详细信息作为字符串获取,但奇数一两个包含指向URL等的链接。这些是原始字符串,不包含html标记,只包含纯字符串。

因此字符串中的网址只是http://www...ect etc,甚至只是www.name... etc

我尝试做的是将它们转换为可点击链接,因此当它们输出到浏览器时,它们实际上是链接而不是用户必须复制和粘贴的字符串URL等。

字符串的一个例子是:

  

Lorem ipsum dolor坐在精神上。 Animi possimus nisi a quis,voluptas adipisci asperiores,earum aut totam sequi necessitatibusrepellat,quasi labore molestiae。 Laboriosam quis vitae unde http://www.websitename.com?title=oy96 natus.earum aut totam sequi necessitatibus repellat,quasi labore molestiae。 Laboriosam quis vitae unde natusearum aut totam sequi necessitatibus repellat,quasi labore molestiae。 Laboriosam quis vitae unde natus

最好将http://www.websitename.com?title=oy96转换为仅包含域名的可点击链接。www.websitename.com

1 个答案:

答案 0 :(得分:0)

刚为您的问题编写了完美的解决方案:

function webAddressesToHTML($text,$label_strip_params=false,$label_strip_protocol=true) {

    $webAddressToHTML = function ($url) use ($label_strip_params,$label_strip_protocol) {
        $label = $url;
        if($label_strip_params) {
            $label = rtrim(preg_replace('/\?.*/', '',$label),"/");
        }
        if($label_strip_protocol) {
            $label = preg_replace('#^https?://#', '', $label);
        }
        return '<a href="'.((!preg_match("~^(?:f|ht)tps?://~i", $url)) ? "http://".$url : $url).'">'.$label.'</a>';
    };

    preg_match_all('@(http(s)?://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@',$text,$matched_urls);
    return str_replace($matched_urls[0],array_map($webAddressToHTML,$matched_urls[0]),$text);
}

参见示例:

$demo = "After the latest show, we went to www.example.com and made some trouble online. https://www.letsfail.net/?a=b gave us their support and also netjunkies.sample is involved. Finally we are in!";

var_dump(webAddressesToHTML($demo));

输出:

string(302) "After the latest show, we went to <a href="http://www.example.com">www.example.com</a> and made some trouble online. <a href="https://www.letsfail.net/?a=b">www.letsfail.net/?a=b</a> gave us their support and also <a href="http://netjunkies.sample">netjunkies.sample</a> is involved. Finally we are in!"

根据您希望获得网址标签的方式,只需将可选参数设置为truefalse即可。如果你真的想剥离获取参数取决于你的用例。