Search code examples
javahtmltagstextareahtmlelements

Textarea content is not rendering properly \n \b \r are not working properlly


I entered some paragraph with text Alignment and saved that in DB. After got the text from DB and display in one DIV tag.I can view the text but Alignment is missing. When I investigate \n \b \r symbols are not reorganized by the browser. How can I solve the issue?


Solution

  • There are several ways to do this.

    Using PHP preg_replace

    You can use PHP preg_replace function to prettify your text. Let's say you stored your text in some variable called $var. You can use following to replace all \n with HTML
    tag.

    $var = "Your text goes here....";
    $var = preg_replace( '/[\n\r]+/',"<br>", $var );
    

    Using HTML pre Tags

    You can simply use HTML pre tag to add some quick formatting to your text. Just bind your text within <pre> tags.