Why won't str_replace php function work for replacing quotes in a string passed from an array, to be used for $_GET

StackOverflow https://stackoverflow.com/questions/22540460

  •  18-06-2023
  •  | 
  •  

Question

I am trying to sanitize my URL, and the GET variable may contain a quotation mark, single or double.

$teststring = $row['story_title'];
$sanitized_test = str_replace("'", "~", $teststring);
echo $teststring . " versus " . $sanitized_test;

What this prints:

'''' versus ''''

What i expect it to print:

'''' versus ~~~~

When $teststring = "''''"; everything works fine. Why is this happening?

Was it helpful?

Solution

The problem was, htmlentities. I had forgotten that for security reasons I was sanitizing the input of the data into a database with html entities, among other functions. When I was testing I just assumed to check what the value of $row['story_title'] was by printing it, and you know what they say about assumptions.

It came to me after I made a duplicate array with the same process and it worked. Went to check my database and there it was, "''''". Oops! Essentially the issue was it wasn't finding any of the single quotes i was trying to match from that string, however when one prints that string it will show quotes.

Ultimately I changed my code to $sanitized_test = str_replace("'", "~", $row['story_id']); and voila! It works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top