angry kiwi
angry kiwi

Reputation: 11445

PHP - find links from particular website and remove

I got a string which has a lot of bad links from bad website and there are also useful links for my user.

I need a way to remove the bad links only. such as method below

remove('regex', badsite.com, ''); // remove all links from badsite.com
remove('regex', viagra.com, ''); // remove links from viagra.com

Upvotes: 1

Views: 405

Answers (2)

Gaurav Porwal
Gaurav Porwal

Reputation: 513

Check this I think this may help you...

<?php
function remove($string) {
  $patterns = array();
  $patterns[0] = '/http:\/\/www.badsite.com/';
  $patterns[1] = '/http:\/\/www.viagra.com/';
  $patterns[2] = '/badsite.com/';
  $patterns[3] = '/viagra.com/';



  $replacements = array();
  $replacements[0] = '**Remove**';
  $replacements[1] = '**Remove**';
  $replacements[2] = '**Remove**';
  $replacements[3] = '**Remove**';

  echo preg_replace($patterns, $replacements, $string);
}

$string = "This is my url http://www.badsite.com and one more dirty site http://www.viagra.com one good site http://www.google.com";

remove($string);
?>

Output -

This is my url Remove and one more dirty site Remove one good site http://www.google.com

Upvotes: 0

azat
azat

Reputation: 3565

Try this

preg_replace('@<a[^<>]*href="(?:http://|https://)(?:badsite\.com|viagra\.com)[^"]*"[^<>]*>@Uis', '', $str);

But the best way for this is not using regex, and using DOM

Upvotes: 1

Related Questions