preg替换所有链接

时间:2010-02-16 22:20:54

标签: php preg-replace hyperlink

$text = "Clip - http://depositfiles.com/files/8b5560fne Mp3 - 
    http://letitbit.net/download/4920.adaf494fbe2b15c34a4733f20/Madonna___The_Power_Of_Good_Bye.mp3.html 
    Madonna - The power of goodbye Your heart is not open, so I must go The spell has been broken...I 
    loved you so Freedom comes when you learn to let go Creation comes when you learn to say no You were 
    my lesson I had to learn I was your fortress you had to burn Pain is a warning that something's wrong 
    I pray to God that it won't be long Do ya wanna go higher? Chorus: There's nothing left to try 
    There's no place left to hide There's no greater power than the power of good-bye Your heart is not 
    open, so I must go The spell has been broken...I loved you so You were my lesson I had to learn I was 
    your fortress Chorus: There's nothing left to lose There's no more heart to bruise There's no greater 
    power than the power of good-bye Bridge: Learn to say good-bye I yearn to say good-bye Chorus: There's 
    nothing left to try There's no more places to hide There's no greater power than the power of good-bye 
    There's nothing left to lose There's no more heart to bruise There's no greater power than the power 
    of good-bye";

我如何在本文中完全删除所有链接?

2 个答案:

答案 0 :(得分:3)

您可以尝试这样简单的事情:

$text = preg_replace("#\S+://\S+#", "", $text);

虽然会在结果字符串中留下双倍空格。你可以处理它,但它会变得稍微复杂一些。我也不会检查删除的文本是否是有效的URL。包含://的任何内容都将被删除。

答案 1 :(得分:1)

一种天真的方法:

preg_replace('/http[^\s]+/', "", $str)

替换任何以“http”开头且由非空格字符组成的字符串,并带有空字符串。

这假设您只获得http。否则,不那么天真(但仍然大多是天真的):

preg_replace('#[a-z]+://[^\s]+#', "", $str)