Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 940
Gisheri Avatar asked Oct 03 '12 08:10

Gisheri


People also ask

How to replace spaces with underscores in php?

if you have a parameter $string and want to replace it's apace to underscore(_). $string = "Hello All."; $newString = str_replace(' ', '_', $string);

How to replace spaces in php?

Answer: Use the PHP str_replace() Function You can simply use the PHP str_replace() function to strip or remove all spaces inside a string.

How do you change spaces to underscores?

Use the String. replaceAll method to replace all spaces with underscores in a JavaScript string, e.g. string. replaceAll(' ', '_') . The replaceAll method returns a new string with all whitespace characters replaced by underscores.


1 Answers

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); 
like image 96
Laurent Brieu Avatar answered Sep 30 '22 13:09

Laurent Brieu