[PHP] Sample regex and function to wrap line breaks in p tags
![[PHP] Sample regex and function to wrap line breaks in p tags](img/ogp.png)
I wanted to output a string containing line breaks wrapped in p tags (paragraphs) in WordPress.
So, here's an introduction to a minimal regex and function.
Table of Contents
Simple
function br_to_p ($int){
$int = str_replace(array("\r\n", "\r", "\n"), "\n", $int); // Unify line break codes to \n
$array = explode("\n", $int); // Split by \n into an array
$str = '';
foreach($array as $p){
$str .= '<p>'.$p.'</p>'."\n"; // Wrap each element with p
}
return $str; // Output
}
Input Example
Input text
Line breaks
will be wrapped in p tags
Output Example
<p>Input text</p>
<p>Line breaks</p>
<p></p>
<p>will be wrapped in p tags</p>
If there are blank lines, they will become empty p tags.
It's up to you to decide if this is good or bad.
Handling Consecutive Line Breaks
Here's also a version that excludes empty lines using regex.
function br_to_p ($int){
$int = str_replace(array("\r\n", "\r", "\n"), "\n", $int); // Unify line break codes to \n
$array = preg_split("/\n+/", $int); // Split by \n into an array
$str = '';
foreach($array as $p){
$str .= '<p>'.$p.'</p>'."\n"; // Wrap each element with p
}
return $str; // Output
}
Input Example
Input text
Line breaks
will be wrapped in p tags
Output Example
<p>Input text</p>
<p>Line breaks</p>
<p>will be wrapped in p tags</p>
Comments
If you found something different in your environment, or know a better way, please feel free to send a comment.




If this was helpful, we appreciate your support!
Any support received will be used for childcare.
Or support us by buying something from the buttons below
(You don't have to buy the linked product.)
Amazon
楽天市場
Yahoo!ショッピング
PR