在PHP中使用Regex我将URL和EMails转换为HTML链接

时间:2017-02-14 01:32:09

标签: php regex

我在这里搜索得很远,我找不到符合我特定需求的东西。

我需要在PHP中使用正则表达式解析一段文本并做两件事。

  1. 将网址转换为HTML链接
  2. 将电子邮件转换为mailto: HTML链接
  3. 我让他们分开工作,但问题是URL转换器会尝试将域名链接到电子邮件地址。如果我先走另一条路,那么电子邮件链接就可以了。 href属性将重新链接,导致HTML损坏。

    以下是我正在使用的内容:

    public function getParsedBodyAttribute()
    {
        $string = $this->body;
    
        $string = preg_replace('/(\S+@\S+\.\S+)/', '<a href="mailto:$1">$1</a>', $string);
    
        return preg_replace('(?!(?!.*?<a)[^<]*<\/a>)(?:(?:https?|ftp|file)://|www\.|ftp\.)[-A-Z0-9+&#/%=~_|$?!:,.]*[A-Z0-9+&#/%=~_|$]', '<a href="http$2://$4" target="_blank" title="$0">$0</a>', $string);
    }
    

1 个答案:

答案 0 :(得分:0)

我认为这会帮助你。

&#13;
&#13;
<?php
//REGEX &copy; https://github.com/virdwait/virdwaitJs
$str = "http://www.google.com , works in ftp://ftp.google.com , then in www.twitter.com , now google.com  and again it is https://www.facebook.com/ and then changed to  :  sagarvd01@gmail.com ";
$str=preg_replace('/([a-zA-Z0-9]{2,}((\!|\#|\$|\%|\&|\'|\*|\+|\-|\/|\=|\?|\^|\_|\`|\{|\||\}|\~|\!|\#|\$|\%|\&|\'|\*|\.)[a-zA-Z0-9]+)*@[a-zA-Z0-9-]+\.[a-zA-Z]{2,6}(\.[a-zA-Z0-9]{2,6}){0,1}){1}/','<a href="mailto:$1">$1</a>',$str);
$str=preg_replace('/((((https:\/\/|http:\/\/|ftp:\/\/){0,1}(www.|ftp.){1})|\s[^www\.]){1}[a-zA-Z0-9-]+\.[a-zA-Z]{2,10}(\.[a-zA-Z]{2,10}){0,1}(\/){0,1}){1}/','<a href="$1">$1</a>',$str);

echo $str;

//return $str
?>
&#13;
&#13;
&#13;

查看演示Here