Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP. Remove Links from Strings

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!

like image 422
user2331090 Avatar asked Jun 07 '13 04:06

user2331090


People also ask

How to remove link from string in PHP?

PHP-Remove-URL-from-string.php $string = 'Hi, visit my website: http://beto.euqueroserummacaco.com'; $string = preg_replace('/\b(https?| ftp|file):\/\/[-A-Z0-9+&@#\/%? =~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);

How to remove hyperlink in word?

To remove a hyperlink but keep the text, right-click the hyperlink and click Remove Hyperlink. To remove the hyperlink completely, select it and then press Delete.


2 Answers

$pattern = "/[a-zA-Z]*[:\/\/]*[A-Za-z0-9\-_]+\.+[A-Za-z0-9\.\/%&=\?\-_]+/i";
$replacement = "";
preg_replace($pattern, $replacement, $string);
like image 176
skparwal Avatar answered Oct 14 '22 17:10

skparwal


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);
like image 42
user2331090 Avatar answered Oct 14 '22 18:10

user2331090