PHP str_replace replace spaces with underscores

Gisheri picture Gisheri · Oct 3, 2012 · Viewed 184k times · Source

Is there a reason that I'm not seeing, why this doesn't work?

    $string = $someLongUserGeneratedString;
    $replaced = str_replace(' ', '_', $string);
    echo $replaced;

The output still includes spaces... Any ideas would be awesome

Answer

Laurent Brieu picture Laurent Brieu · Oct 3, 2012

I'll suggest that you use this as it will check for both single and multiple occurrence of white space (as suggested by Lucas Green).

$journalName = preg_replace('/\s+/', '_', $journalName);

instead of:

$journalName = str_replace(' ', '_', $journalName);