Converting paragraph tags with RegEx
I need to replace all <p>
tags with <br />
tags within a string.
The problem is that the <p>
tag can have attributes in it , such as <p align="center">
so I want to delete all occurrences of an opening tag of a paragraph, no matter what attributes are in it, and replace them with <br />
.
I am using PHP and had no success getting to the right e开发者_JAVA百科xpression with the preg_replace
function.
Any help would be appreciated!
Joel
preg_replace('#<p\b[^>]*>#i', '<br />', $stringContainingParas)
The above should give you what you want. It matches any open angle bracket, then either a p or a P (it is case insensitive from the i following the closing delimiter), then zero or more characters that are not a closing angle bracket, and then finally the closing angle bracket.
preg_replace('#<p\b.*?>#i', '<br />', $stringContainingParas)
Will do just as good a job. Instead of matching any character that is not a closing angle bracket, it matches any character, but not greedily so that the closing angle bracket matches the next part of the regex if it is encountered anywhere along the line.
Assuming that you will never have a >
inside an attribute to a <p>
tag, you could do the following:
$result = preg_replace('/<p\b[^>]*>/s', '<br />', $subject);
精彩评论