Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for new line within html tag [duplicate]

Tags:

regex

php

I am using regex to replace p tag if have html attributes with p tag without having attributes and regex is:

$html = preg_replace("/<p[^>]*>(.+?)<\/p>/i", "<p>$1</p>", $html);

Regex is working good if p tag have not any new line like

<p style="text-align: center;">It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout</p>

But when p tag have new line then above regex is not working. For an example

<p style="text-align: center;">It is a long established fact that a reader will be
distracted by the readable <br />
content of a page when looking at its layou</p>

So could someone suggest that what changes will be required in above regex so that they work properly if p tag have string including new lines?

like image 305
Katty Avatar asked Sep 01 '25 01:09

Katty


1 Answers

If you must, use

$html = preg_replace("/<p[^>]*>(.+?)<\/p>/is", "<p>$1</p>", $html);
#                                          ^

which enables the singleline mode, aka the dot matches newline characters as well. The usual warning not to use regular expressions on HTML tags applies nevertheless.
See a demo on regex101.com.

like image 178
Jan Avatar answered Sep 02 '25 16:09

Jan