89

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

0

4 Answers 4

209

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);
Sign up to request clarification or add additional context in comments.

5 Comments

It uses a Regular Expression to match a class of strings in a given pattern, and replaces it with a substitution sequence when matched.
There is a bug in this version, it will only match groups of more than one space.
@LucasGreen, you right ! Correct one is : preg_replace('/\s+/', '_', $journalName);
you probably want trim as well: preg_replace('/\s+/', '_', trim($journalName));
For UTF-8 encoding use preg_replace('/\s+/u', '_', $journalName)
23

Try this instead:

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

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

Comments

15

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

Comments

-2

Try this instead:

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

to remove white space

1 Comment

How does this differ from the code provided in the question (other than variable names)? $replaced = str_replace(' ', '_', $string);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.