Skip to content

Commit 3263257

Browse files
Formatting: Add strip_html_newlines() function to preserve newlines in specific HTML elements
1 parent 609f25f commit 3263257

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/wp-includes/formatting.php

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -868,6 +868,52 @@ function shortcode_unautop( $text ) {
868868
return preg_replace( $pattern, '$1', $text );
869869
}
870870

871+
function strip_html_newlines( $text ) {
872+
if ( ! str_contains( $text, "\n" ) && ! str_contains( $text, "\r" ) ) {
873+
return $text;
874+
}
875+
876+
$preserve_newlines_elements = array( 'pre', 'code', 'kbd', 'script', 'style' );
877+
878+
$textarr = wp_html_split( $text );
879+
$changed = false;
880+
$skip = false;
881+
882+
foreach ( $textarr as $i => $chunk ) {
883+
if ( '' === $chunk ) {
884+
continue;
885+
}
886+
887+
if ( 0 !== $i % 2 ) {
888+
foreach ( $preserve_newlines_elements as $element ) {
889+
if ( stripos( $chunk, '<' . $element ) === 0 ) {
890+
$skip = true;
891+
break;
892+
}
893+
if ( stripos( $chunk, '</' . $element . '>' ) === 0 ) {
894+
$skip = false;
895+
break;
896+
}
897+
}
898+
continue;
899+
}
900+
901+
if ( ! $skip ) {
902+
$stripped = preg_replace( '/[\n\r]+/', ' ', $chunk );
903+
if ( $stripped !== $chunk ) {
904+
$textarr[ $i ] = $stripped;
905+
$changed = true;
906+
}
907+
}
908+
}
909+
910+
if ( $changed ) {
911+
return implode( '', $textarr );
912+
}
913+
914+
return $text;
915+
}
916+
871917
/**
872918
* Checks to see if a string is utf8 encoded.
873919
*

0 commit comments

Comments
 (0)