Adding a class to each paragraph tag using PHP Regex

The $content variable contains a string with HTML paragraph tags such as:

$content = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Aliquam mauris diam, gravida eget finibus varius.</p>";

How can I add a class “textStyle” to each paragraph using PHP regex so that it looks like this:

$content = "<p class="textStyle">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p class="textStyle">Aliquam mauris diam, gravida eget finibus varius.</p>";

Here is what I have tried so far:

<?php

$content = "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    <p>Aliquam mauris diam, gravida eget finibus varius.</p>";

    $pattern = "/(<p)/";

    $replace = '<p class="textStyle"';

    preg_replace($pattern, $replace, $content);

?>


Source: regex

Leave a Reply