Front-End & Daily

[PHP] Sample regex and function to wrap line breaks in p tags

[PHP] Sample regex and function to wrap line breaks in p tags

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.

After reviewing the content, we will publish it, omitting personal information.

Enter your name and email address

Please enter if you would like a reply via email.

Personal information provided will not be disclosed. It will only be used for replies.

It will be sent directly. Please confirm and "Send".

If this was helpful, we appreciate your support!
Any support received will be used for childcare.

Send support via OFUSE


Or support us by buying something from the buttons below
(You don't have to buy the linked product.)

Amazon

楽天市場

Yahoo!ショッピング

PR

As an Amazon Associate, "Ken" earns from qualifying purchases.

Share

Share on Twitter Share on Facebook Share on LINE Share on Hatena Bookmark