14

I have the following code

$s = '\n [email protected] \n ';
$s = str_replace('\n', '', $s);

echo $s;

I want to replace the '\n' char with '' but it's not working with the above code. I have found that as \n is the new line char with ascii value 10 by echo ord(substr($s, 0, 1)); it is not working. It's not clear to me what is the exact reason behind not working the above code. please help.

2
  • 3
    Use double quote : "\n" instead or escape the \ Commented Nov 8, 2016 at 12:42
  • 1
    Check out php.net/manual/en/language.types.string.php - it explains the different ways strings can be specified in PHP. Also trim() might be the function you're after instead of str_replace(). Commented Nov 8, 2016 at 12:49

2 Answers 2

34

You need to place the \n in double quotes. Inside single quotes it is treated as 2 characters '\' followed by 'n'

Try below code:

$s = "\n [email protected] \n";
$s = str_replace("\n", '', $s);

echo $s;
Sign up to request clarification or add additional context in comments.

2 Comments

First line should also use double quotes - current code won't change the string at all.
yes there is typo , updated the answer thanks @steve
5

You have to use double quotes. \n is not interpreted as newline with single quotes.

Comments

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.