PHP:从字符串中删除 URL

12

我有很多字符串(Twitter推文),在回显它们时我想删除链接。

我无法控制字符串,即使所有链接都以http开头,它们可能以“ /”或“ ;”结束,并且可以跟随空格或不跟随空格。此外,有时链接和其前面的单词之间没有空格。

这样的字符串示例:

The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge

我尝试过使用preg_replace,但无法得出适用于所有异常情况的解决方案:

<?php echo preg_replace("/\http[^)]+\;/","",$feed->itemTitle); ?>

你有什么想法应该怎么做?

编辑:我已经尝试过

<?php echo preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)‌​?)@', ' ', $feed->itemTitle); ?>

但仍然没有成功。

编辑2:我找到了这个:

<?php echo preg_replace('^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-‌​\.\?\,\'\/\\\+&amp;%\$#_]*)?$^',' ', $feed->itemTitle); ?>

这个方法可以按预期删除链接,但是当链接前面没有空格时,它也会删除整个字符串。


@DavidThomas 抱歉,打错字了!感谢Theftprevention! - MagTun
@gronostaj,感谢提供链接。我对Php的了解非常有限,正在努力摆脱最受欢迎的答案。 - MagTun
@Arone,你不需要那段PHP代码,只需要正则表达式来匹配URL。 - gronostaj
3
这是我见过最常用的正则表达式,它可能也适用于您:$feed->itemTitle = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', ' ', $feed->itemTitle); - Burak
显示剩余7条评论
3个回答

24
如果您想删除链接及其后面的所有内容,例如示例中所示的"via thing",下面的内容可能会有所帮助:
$string = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
$regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?).*$)@";
echo preg_replace($regex, ' ', $string);
如果您想保留它们:
$string = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
$regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@";
echo preg_replace($regex, ' ', $string);

非常感谢Burak,这正是我所需要的! - MagTun

3
我会这样做:
$input = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
$replace = '"(https?://.*)(?=;)"';

$output = preg_replace($replace, '', $input);
print_r($output);

它也适用于多次出现的情况:
$output = preg_replace($replace, '', $input."\n".$input);
print_r($output);

感谢@jamb的回答,但有时链接并不以“;”结尾,因此我需要找到一个更全局的正则表达式。 - MagTun

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接