[php] PHP str_replace replace spaces with underscores

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

This question is related to php str-replace

The answer is


For one matched character replace, use str_replace:

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

For all matched character replace, use preg_replace:

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

Try this instead:

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

to remove white space


Try this instead:

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

Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).