0

I am trying to print a preg_replace result outside the loop it is made.

This is my code

$search = "Lola and Chris";
$query_gdpr_names = "select name FROM gdpr_names";
$result_gdpr_names = mysqli_query($connect, $query_gdpr_names);
            
while ($row_gdpr_names = mysqli_fetch_assoc($result_gdpr_names)) {
    $name = $row_gdpr_names['name'];
    $regex = "/\b" . $name . "\b/ui";
    $search = preg_replace($regex, 'removed', $search);
}
echo $search;

If I try to print the $search inside the loop it will print each iteration as expected. But if I try to print it outside the loop, it comes empty.

If I try to use str_replace instead, it will print outside correctly

$search = str_replace($name, 'removed', $search);

Any ideas what I am doing wrong with the preg_replace?

Phil
  • 157,677
  • 23
  • 242
  • 245
lStoilov
  • 1,256
  • 3
  • 14
  • 30
  • 2
    Not sure if it's the problem, but it may cause problems if the name includes certain characters, you may want to escape it before using it - https://stackoverflow.com/questions/1531456/is-there-a-php-function-that-can-escape-regex-patterns-before-they-are-applied – Nigel Ren Sep 14 '20 at 07:13
  • 1
    Strictly speaking, you should _never_ have an empty `$search` string from that loop, since it replaces a match with the text `removed`. You should check your result set. If, for example, it had every letter of the alphabet as a name entry, then your replacement logic would remove all letters. You should step through the loop in debug mode and check. – Tim Biegeleisen Sep 14 '20 at 07:17
  • 2
    Can't reproduce this (with standard ASCII names) ~ https://3v4l.org/i1VO7 – Phil Sep 14 '20 at 07:17
  • I suspect your actual code has a typo somewhere in one of your variable names. Make sure you can see any and all errors. [How can I get useful error messages in PHP?](https://stackoverflow.com/questions/845021/how-can-i-get-useful-error-messages-in-php) – Phil Sep 14 '20 at 07:19
  • 1
    @NigelRen, you were absolutely right... There was one record in the database which contained a slash. Thanks! – lStoilov Sep 14 '20 at 07:41
  • `"Little/Bobby/Tables"`? – Phil Sep 14 '20 at 08:41
  • @Phil, didn't get that/ – lStoilov Sep 14 '20 at 10:35
  • https://xkcd.com/327/ Just saying that a slash in a name field seems kinda weird – Phil Sep 14 '20 at 12:41
  • @Phil, I got what you mean :) Indeed I need to sanitize it. And yes the problem was that a record in the name field was something like this name/name. – lStoilov Sep 15 '20 at 05:01

1 Answers1

0

So the problem seems to be with one of the records having a slash. Removing the slash fixed the problem.

It was fixed based on @NigelRen comment. All credits to him!

lStoilov
  • 1,256
  • 3
  • 14
  • 30