Skip to content

Instantly share code, notes, and snippets.

@fjarrett
Last active April 6, 2022 16:57
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fjarrett/ecddd0ed419bb853e390 to your computer and use it in GitHub Desktop.
Save fjarrett/ecddd0ed419bb853e390 to your computer and use it in GitHub Desktop.
Inverse behavior to the wpautop() function found in WordPress
<?php
/**
* Replaces paragraph elements with double line-breaks.
*
* This is the inverse behavior of the wpautop() function
* found in WordPress which converts double line-breaks to
* paragraphs. Handy when you want to undo whatever it did.
*
* @see wpautop()
*
* @param string $pee
* @param bool $br (optional)
*
* @return string
*/
function fjarrett_unautop( $pee, $br = true ) {
// Match plain <p> tags and their contents (ignore <p> tags with attributes)
$matches = preg_match_all( '/<(p+)*(?:>(.*)<\/\1>|\s+\/>)/m', $pee, $pees );
if ( ! $matches ) {
return $pee;
}
$replace = array( "\n" => '', "\r" => '' );
if ( $br ) {
$replace['<br>'] = "\r\n";
$replace['<br/>'] = "\r\n";
$replace['<br />'] = "\r\n";
}
foreach ( $pees[2] as $i => $tinkle ) {
$replace[ $pees[0][ $i ] ] = $tinkle . "\r\n\r\n";
}
return rtrim(
str_replace(
array_keys( $replace ),
array_values( $replace ),
$pee
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment