【问题标题】:php: Remove URL from stringphp:从字符串中删除 URL
【发布时间】:2014-08-26 15:06:45
【问题描述】:

我有很多字符串(推特推文),当我回显它们时,我想从中删除链接。

我无法控制字符串,即使所有链接都以 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 对不起:一个错字!感谢防盗!
  • @gronostaj,感谢您的链接。我对 Php 的了解非常有限,我正在努力摆脱最受好评的分析器。
  • @Arone 你不需要那个 PHP 代码,只需要匹配 URL 的正则表达式。
  • 这是我见过的最常见的正则表达式,可能也适合你:$feed-&gt;itemTitle = preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', ' ', $feed-&gt;itemTitle);

标签: php regex string


【解决方案1】:

如果您想删除所有内容、链接和链接之后的内容,例如示例中的 via,以下内容可能会对您有所帮助:

$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,这正是我所需要的!
【解决方案2】:

我会这样做:

$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 的回答,但是,有时链接不以“;”结尾所以我需要找到一个更全球化的正则表达式。
猜你喜欢
  • 1970-01-01
  • 2012-07-18
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多