Regex (not advised):
If you must use regex, you can try something like this. It doesn't match the abilities of DOM manipulation (see the rest of my answer below), but if you are sure your <p>
tags are consistent without any existing classes, then you can try this:
$pattern = "/<p([> ])/";
$replace = '<p class="textStyle"$1';
$content = preg_replace($pattern, $replace, $content);
This will match only <p>
and <p
so as to try to keep any other attributes you may have. However, it is difficult using regex to properly handle more complicated situations like <p id="row1" class="class1">
or q><p
(some emoji face) .
DOM Manipulation:
For a much better solution (that doesn't use regex) you can instead do the following. The reason this is superior is because you can also replace class attributes, and automatically maintain other attributes. Plus, if there are HTML validation errors, the DOMDocument
object will note these.
<?php
$content = "<p class=\"oldClass\">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p style=\"color:red\">Aliquam mauris diam, gravida eget finibus varius.</p>";
$dom = new DOMDocument();
$dom->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
// Evaluate P tags in HTML. This just shows
// that you can be more selective on your tags
$xpath = new DOMXPath($dom);
$tags = $xpath->evaluate("//p");
// Loop through all the found tags
foreach ($tags as $tag) {
// Set class attribute
$tag->setAttribute("class", "textStyle");
}
// Save the HTML changes
$content = $dom->saveHTML();
Result:
<p class="textStyle">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<p style="color:red" class="textStyle">Aliquam mauris diam, gravida eget finibus varius.</p></p>
Pay special attention to this bit:
loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
without this, you will end of up HTML wrapper tags.