'Replace paragraph HTML element with line breaks (\r\n\r\n) in php

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()?



Solution 1:[1]

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

Solution 2:[2]

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.....

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Estail Se
Solution 2 jspit