PHP。从字符串中删除链接

时间:2013-06-07 04:37:57

标签: php string replace

Helllo,我在网站上有一些用户生成的内容。我想使用php函数删除它的链接。

例如,我有以下字符串:

"text1 http://link1 text2 www.link2 text3 link3.com text4"

是否有一种简单的方法来检测包含http:,www。,。com的单词并将其从文本中删除?或者还有其他任何清理链接文本的好方法吗?

感谢您的时间!

2 个答案:

答案 0 :(得分:12)

$pattern = "/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i";
$replacement = "";
preg_replace($pattern, $replacement, $string);

答案 1 :(得分:5)

哦,我找到了答案。

function cleaner($url) {
  $U = explode(' ',$url);

  $W =array();
  foreach ($U as $k => $u) {
if (stristr($u,'http') || (count(explode('.',$u)) > 1)) {
  unset($U[$k]);
  return cleaner( implode(' ',$U));
}
}
  return implode(' ',$U);
}

$url = "Here is another funny site www.tinyurl.com/55555 and http://www.tinyurl.com/55555 and img.hostingsite.com/badpic.jpg";
echo "Cleaned: " . cleaner($url);