10

Helllo, I have some user-generated content on the website. I want to remove links out of it using php functions.

For example I have the following string:

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

Is there a simple way to detect words, containing http:, www., .com and to remove them from text? Or is there any other good way of cleaning the text from links?

Thank you for your time!

2 Answers 2

13
$pattern = "/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i";
$replacement = "";
preg_replace($pattern, $replacement, $string);
Sign up to request clarification or add additional context in comments.

1 Comment

Works well for basic simple URLs. When the URLs contain special characters such as { or }, it fails. But it's great for removal of SEO friendly links.
5

Oh, I found the answer.

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.