用 PHP 替换其他单词的链接


Replace links with other words with PHP

我今天运行一个约会网站,为了不失去会员,我想阻止用户互相发送Facebook链接。他们有一个文本区域,他们在其中编写对话,并将其插入到MySQL数据库中。

现在,当他们写他们的Facebook地址时,我想这样做:

 https://www.facebook.com/my.nick

在封面中替换为以下文字:

 i like you

有什么好的PHP例子可以做到这一点吗?/切尔兹

您可以将

preg_replace用作

$str = "hello www.facebook.com. this is my fb page http://facebook.com/user-name.
Here is another one for the profile https://www.facebook.com/my-profile/?id=123.
";
$str = preg_replace('"'b((https?://|www)'S+)"', 'my new text',$str);
echo $str ;
output // hello my new text this is my fb page my new text
          Here is another one for the profile my new text

或更好地使用

$str = preg_replace('/'b((https?:'/'/|www)'S+)/i', 'my new text',$str);


 /'b((https?:'/'/|www)'S+)/i
'b assert position at a word boundary (^'w|'w$|'W'w|'w'W)
1st Capturing group ((https?:'/'/|www)'S+)
    2nd Capturing group (https?:'/'/|www)
        1st Alternative: https?:'/'/
            http matches the characters http literally (case insensitive)
            s? matches the character s literally (case insensitive)
                Quantifier: Between zero and one time, as many times as possible, giving back as needed [greedy]
            : matches the character : literally
            '/ matches the character / literally
            '/ matches the character / literally
        2nd Alternative: www
            www matches the characters www literally (case insensitive)
    'S+ match any non-white space character [^'r'n't'f ]
        Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])