Search code examples
phphtmlline-breakspre

Php display as a html text the new line \n


I'm using echo to display result but the result contains line breaks /n /t /r.

I want to know if the result has is \n or \t or \r and how many. I need to know so I can replace it in a html tag like <p> or <div>.

The result is coming from on other website.

In pattern CreditTransaction/CustomerData: 



        Email does not contain any text

In pattern RecurUpdate/CustomerData:      



    Email does not contain any text

In pattern AccountInfo: 

I want like this.

In pattern CreditTransaction/CustomerData: 
    \n
    \n
    \n  
      \n\tEmail does not contain any text
      \n
In pattern RecurUpdate/CustomerData:      
    \n
    \n
      \n
    \n\tEmail does not contain any text

\n\tIn pattern AccountInfo: 

Solution

  • Your question is quite unclear but I'll do my best to provide an answer.

    If you want to make \n, \r, and \t visible in the output you could just manually unescape them:
    str_replace("\n", '\n', str_replace("\r", '\r', str_replace("\t", '\t', $string)));

    Or if you want to unescape all escaped characters:
    addslashes($string);

    To count how many times a specific character/substring occurs:
    substr_count($string, $character_or_substring);

    To check if the string contains a specific character/substring:
    if (substr_count($string, $character_or_substring) > 0) { // your code }
    Or:
    if (strpos($string, $character_or_substring) !== false) { // notice the !== // your code }

    As mentioned earlier by someone else in a comment, if you want to convert the newlines to br tags:
    nl2br($string);

    If you want to make tabs indenting you could replace all tabs with &emsp;:
    str_replace("\t", '&emsp;', $string);