Image blacklist - test a string against a blacklist in PHP


/ Published in: PHP
Save to your folder(s)

I was working on a site that pulled in and republished a bunch of RSS feeds. Some contained duff images such as blank gifs that I needed to block so I wrote this function to compare the url of an image against a blacklist


Copy this code and paste it in your HTML
  1. /////////////////////////////
  2. // Function
  3.  
  4. // compare string to a blacklist of image url fragments to avoid
  5. function imageBlacklist($str){
  6. // words to filter
  7. $badwords = array( "//feeds.", "b.gif", "//api." );
  8. $result_of_filter = 0;
  9. foreach ($badwords as $value) {
  10. //echo($value);
  11. $find_pos = strpos($str,$value);
  12. if ($find_pos > 0) {
  13. $result_of_filter = 'blacklisted';
  14. break;
  15. }
  16. }
  17. unset($value); // break the reference with the last element
  18. return $result_of_filter;
  19. }
  20.  
  21.  
  22. /////////////////////////////
  23. // usage
  24.  
  25. // $test_this contains an example string — an image URL
  26. $test_this = "http://example.com/images.b.gif";
  27. // invoke the function to check our example string
  28. $test_result = imageBlacklist($test_this);
  29. // if the function returns blacklist we know a match was found
  30. if ($test === 'blacklisted') {
  31. // use the fall back image url instead
  32. echo("<img src='http://example.com/backup-image.png' alt='' />");
  33. } else {
  34. // the url is not on black list so use for our image
  35. echo("<img src='".$test_this."' alt='' />");
  36. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.