1

I am inserting this text What is <br/> PHP? into the database

Now I want to show this text as a line break. Like below:

What is
PHP?

I am using PHP nl2br() function but it's not working. I am getting the value like this:

What is <br/> PHP?

How can I solve it?

Thank You.

Xatenev
  • 6,383
  • 3
  • 18
  • 42
Shibbir Ahmed
  • 161
  • 2
  • 12

2 Answers2

1

A question comes up here... where are you inserting this text (string) ?

If you are injecting it as HTML you'll get the desired result in the rendered page.

I assume this is not the case: you want HTML line breaks turned into newlines.

So...


nl2br()converts newlines into <br />: that's the opposite you want to do

http://php.net/manual/en/function.nl2br.php

Just use str_replace:

$out = str_replace( "<br/>", "\n", $in );

Where $in is the input string and $out is the desired output

http://php.net/manual/en/function.str-replace.php

Just a couple of things to note:

1) the above code will work with HTML line breaks <br/>, not if you have <br>, or <br />

If this is an issue you may pass the function array of strings and array of their replacements. This is well documented in the link above.

2) If you use the code snipped I wrote above you'll end having two spaces in the resulting string:

What is  (with trailing space)

 PHP (with leading space)

Paolo
  • 15,233
  • 27
  • 70
  • 91
  • "the above code will work with HTML line breaks
    , not if you have
    , or
    " ==> `
    ` **is** a html line break. you probably mean XHTML line break or something like that.
    – Xatenev May 11 '17 at 07:43
  • @Xatenev you're right: I've made the code snippet using the HTML (XHTML) line break tag in the OP answer for simplicity. I take care to point out that line breaks may have different syntax (note nr. 1) – Paolo May 11 '17 at 07:46
0

Just use css instead of server-side transformations:

p {
  white-space: pre-line;
}
<p>I am inserting this text What is 
               PHP? into the database
</p>

<p>Now I want to show this text as a line break. Like below:</p>

<p>What    is 
PHP?</p>
Qwertiy
  • 19,681
  • 15
  • 61
  • 128