Last active
April 6, 2022 16:57
-
-
Save frankiejarrett/ecddd0ed419bb853e390 to your computer and use it in GitHub Desktop.
Inverse behavior to the wpautop() function found in WordPress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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