84

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

Gisheri
  • 1,645
  • 2
  • 18
  • 27

4 Answers4

205

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);
neilco
  • 7,964
  • 2
  • 36
  • 41
Laurent Brieu
  • 3,331
  • 1
  • 14
  • 15
23

Try this instead:

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

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

Lucas Green
  • 3,951
  • 22
  • 27
12

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);
Ravi Patel
  • 641
  • 1
  • 10
  • 18
-2

Try this instead:

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

to remove white space

IsaacP
  • 5
  • 2
  • 2
    How does this differ from the code provided in the question (other than variable names)? `$replaced = str_replace(' ', '_', $string);` – Ash Oldershaw Mar 24 '21 at 16:22