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?

9
  • 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 - stackoverflow.com/questions/1531456/… Commented Sep 14, 2020 at 7: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. Commented Sep 14, 2020 at 7:17
  • 2
    Can't reproduce this (with standard ASCII names) ~ 3v4l.org/i1VO7 Commented Sep 14, 2020 at 7: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? Commented Sep 14, 2020 at 7:19
  • 1
    @NigelRen, you were absolutely right... There was one record in the database which contained a slash. Thanks! Commented Sep 14, 2020 at 7:41

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.