Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
I have a string "First line | second line | third line" How can I replace | with a new line character?
"First line | second line | third line"
|
new line
I'm trying to use preg_replace but with no liuck
preg_replace
here it is
str_replace('|',"\n",$string);
when \n is placed in double qouted string it changes to a new line
Add a comment
Use this:
str_replace('|', PHP_EOL, $str);
You should use PHP_EOL instead of "\n" because PHP_EOL will always work on all server platforms. (NB. Windows uses "\r\n" and unix/linux uses "\n").
PHP_EOL
"\n"
"\r\n"
Using strtr is a tad faster than str_replace or preg_replace.
strtr
str_replace
echo strtr($string,'|', "\n");
Mind the double quotes around the \n.
\n
Also, if you want to output HTML, a newline char is not sufficient, you need to replace it with <br /> tags.
<br />
echo str_replace("|", "<br />\n", $string);
There is more generic case where e.g. '' serves as replacwment string:
// Provides: Hll Wrld f PHP $vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]; $onlyconsonants = str_replace($vowels, "", "Hello World of PHP");
Required, but never shown
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.
Explore related questions
See similar questions with these tags.