PHP str_replace replace spaces with underscores

PhpStr Replace

Php Problem Overview


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

Php Solutions


Solution 1 - Php

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);

Solution 2 - Php

Try this instead:

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

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

Solution 3 - Php

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);

Solution 4 - Php

Try this instead:

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

to remove white space

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGisheriView Question on Stackoverflow
Solution 1 - PhpLaurent BrieuView Answer on Stackoverflow
Solution 2 - PhpLucas GreenView Answer on Stackoverflow
Solution 3 - PhpRavi PatelView Answer on Stackoverflow
Solution 4 - PhpIsaacPView Answer on Stackoverflow