2014-07-05 236 views
4

我有很多字符串(推特推文),我想从中删除链接,当我回应他们。php:从字符串中删除URL

我无法控制字符串,即使所有链接都以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); ?> 

其删除链接的预期,但它也删除整个字符串时,没有链接和它前面的单词之间的空间。

+1

相关:什么是最好的正则表达式来检查一个字符串是否是一个有效的URL?](http://stackoverflow.com/q/161738/1937994) – gronostaj

+0

@DavidThomas对不起:一个错字!感谢Theftprevention! – Enora

+0

@gronostaj,感谢您的链接。我对Php的了解非常有限,我正试图从最高优先级的anser中找到我的出路。 – Enora

回答

11

如果你想通过东西去除一切,链接和链接后,喜欢你例如,以下可帮助您:

$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); 
+0

非常感谢布拉克,这正是我需要的! – Enora

1

我会做这样的事情:

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

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

它适用于多种occurances太:

$output = preg_replace($replace, '', $input."\n".$input); 
print_r($output); 
+0

谢谢@jamb的回答,但是,有时链接不会以“;”结尾。所以我需要找到一个更全局的正则表达式。 – Enora