Home > Software engineering >  Replace paragraph HTML element with line breaks (\r\n\r\n) in php
Replace paragraph HTML element with line breaks (\r\n\r\n) in php

Time:03-03

Most answers here are about converting line breaks to <p> but I'm looking to do the opposite. I need <p> to be \r\n\r\n.

Because the WCFM marketplace plugin for WordPress is forcing the use of HTML elements but I need to output my description as JSON object as below, without HTML.

{
    "name": "Hijo",
    "description": "<p>Too cute to avoid. You'd so wanna bring her home.</p><p>Each of our pets is .....",
}

Or is there an opposite function to wpautop()?

CodePudding user response:

you can use preg_match function to find and replace the <p> with \r\n, an </p> with blank space

CodePudding user response:

You can just use strtr to swap the strings.

$description = "<p>Too cute to avoid. You'd so wanna bring her home.</p><p>Each of our pets is </p><p>3rd Line.....";

$descriptionLf = strtr($description,['<p>' => '','</p>' => "\r\n\r\n"]);

echo '<pre>'.$descriptionLf.'</pre>';

Note: The special characters like \n must be in double quotes.

Output:

Too cute to avoid. You'd so wanna bring her home.

Each of our pets is 

3rd Line.....
  • Related