0

In the following lines of code, how can I convert ereg_replace to preg_replace, now that ereg_replace is deprecated.

I have a file called badwords.txt which contains a long range of phrases / words (one per line) which are likely to be spam (these could contain any characters). I use this code to calculate the number of likely-to-be-spam words and then decide what to do with the referrer.

$fh = fopen("badwords.txt","r"); //Open the file that contains the words
while($word = fgets($fh,4096))
{
$text = ereg_replace(trim($word),"#####",$text); 
}
$offence = substr_count($text, "#####");

I get that if it was:

$text = ereg_replace('[^A-Za-z0-9_]', '######', $text );

then it would become:

$text = preg_replace('/[^A-Za-z0-9_]/', '######', $text );

However, I can't make the extra escapes work with my code above. When I run the ereg_replace code I get an error but the data displays nonetheless. When I switch it to preg_replace(trim($word),"#####",$text); nothing shows.

Grateful for any pointers!

Simeon
  • 848
  • 1
  • 11
  • 34
  • 1
    `preg_replace(trim($word)` -- if `$word` is just a plain word, then why use ereg or preg; you can just use `str_replace()`. If `$word` is a regular expression then you need to make sure it is wrapped in delimiters, same as the difference between your previous examples. – Spudley Apr 03 '14 at 13:02
  • Thanks - I've updated the post to include a bit more detail. $word could be any different string that is often included in spam - so it could be ` – Simeon Apr 03 '14 at 13:09
  • Yes, `str_replace()` is probably better unless you are actually using regular expressions. One thing to be aware of is that if the `$word` string includes any regex special characters (eg dots, slashes, etc) then these will be treated as part of a regular expression if you pass them directly into ereg or preg functions. eg a dot will be interpreted as "any single character". In many cases this may prevent it from matching what you expect it to. For this reason, `str_replace()` is probably better, but if you do need to use preg, then you should also use `preg_quote()` to escape them first. – Spudley Apr 03 '14 at 13:23

0 Answers0