Home > front end >  PHP replacing break lines but still show new line
PHP replacing break lines but still show new line

Time:01-31

I have a simple HTML text, each section divided with <br><br>.

*e.g. Lorem ipsum<br><br>
Another lorem ipsum<br><br>
Third section...*

I am sending this text via JSON to an android app, so it is sending it also with <br> tags, because they are needed to show the sections correctly separated in the app.

The problem is, the Google text speech is reading also those
tags.

I want to get rid of them, but still keep the line breaks there.

I manage that text in PHP and I tried:

$txt = preg_replace('<br>', '\r\n', $mytxt);$final = strip_tags($txt);

But this removes the line breaks completely, so the final text is in one piece and it also replaces ANY br word in the text, even if I asked to replace <br>, so that is strange.

So how can I keep the line breaks but get rid of html tags?

CodePudding user response:

Your regular expression is wrong. Try this:

/**
* Convert BR tags to nl
*
* @param string The string to convert
* @return string The converted string
*/
function br2nl($string)
{
    return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);
}

Credits: This code snippet comes from the comments from the php site. https://www.php.net/manual/en/function.nl2br.php

CodePudding user response:

Strip tags might help you...

<?php

    $mytxt = '*e.g. Lorem ipsum<br><br>
    Another lorem ipsum<br><br>
    Third section...*';

    $final = strip_tags($mytxt);

If you were to echo this in your browser for example, it would appear that there are no new lines, but if you were to view the source of your page you would see that the newlines are infact still intact.

Further information: https://www.php.net/manual/en/function.strip-tags.php

  •  Tags:  
  • Related