用PHP替换其他单词的链接

时间:2014-04-05 21:38:55

标签: php

我今天正在运行一个约会网站,为了不丢失会员我想阻止用户互相发送facebook链接。 他们有一个textarea,他们在那里编写会话,并将其插入到MySQL数据库中。

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

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

将替换为涵盖中的以下文字:

 i like you

有什么好的PHP示例可以做到这一点吗? / Cheerz

1 个答案:

答案 0 :(得分:2)

您可以将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])
相关问题