ilmiont
ilmiont

Reputation: 2161

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.

Upvotes: 0

Views: 969

Answers (2)

UltraInstinct
UltraInstinct

Reputation: 44464

Use preg_replace.

$string = "key  , value";
echo "'" . preg_replace("/\s*,\s*/", "', '", $string) . "'";

On a serious note, consider using prepared statements. Hacks like this can get you in trouble some day or the other.

Upvotes: 1

Cthulhu
Cthulhu

Reputation: 1372

Make that

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

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

Upvotes: 2

Related Questions