Search code examples
phpsqlstringstr-replacequotes

str_replace() adding an extra space to its input


Having a strange issue I can't figure out after several minutes of fiddling.

    $quotifiedValues = "'" . str_replace(",", "', '", $string) . "'";

I have this line to quote things ready for SQL.

Lets assume $string = "key, value".

$quotifiedValues = should become "'key', 'value'".

What it actually becomes though is "'key', ' value'".

The crucial thing here is the presence of an extra space. The word value is prefixed by an extra space. I have checked the inputs and, sure enough, no extra space is there. Yet I cannot eliminate it from the output of str_replace(). Any advice on what is going on is much appreciated.


Solution

  • Make that

    $quotifiedValues = "'" . str_replace(", ", "', '", $string) . "'";
    

    Note that we replace ", " now instead of ",".