PHP,从数据库处理字符串,更改<p>

I'm trying to something really easy but I'm confused...

I'm getting a string in php (from a database) that looks like this when Inspect the element with chrome (also in the database, the string is like this) :

$text=

    <p><strong>Title</strong></p>
    <p>text1</p>
    <p>text2</p>
    <p>text3</p>
    <p>text4</p>
    <p><strong>Title2</strong></p>
    .....

I would like to change all the <p> to <p class ="newclass"> and show the text in the browser in the right way.

I tried different ways like this one:

$newtext = preg_replace('/\b<p>\b/u', '<p class = "newclass">', highlight_string($text, true));
echo $newtext;

but that doesn't works. I tried more example but all of theme didn't works.

So, basically I'm getting some text from a database, and I need to change all <p> to a specific new class and echo again in the right way.

Thank you very much

You can use substr_replace to accomplish this task. It is fairly simple.

$text = '<p>';
$class = ' class="class_name">';

echo substr_replace($text, $class, -1);

This code will take the original string, $text, substract -1 from it, and add the second string, $class, to the end of your string (in this case it will be before the >).

The first param is the original string, the one you are pulling from the database, with <p>.

The second param is the addition to the string you are wanting to, and you can change it to reflect whatever need you have.

The third param is the position of where to add the text. You note that the number is negative, this will mean that the script will look for the end of the string to add the extra content, if you change it to a positive number it will start from the beginning.

start

If start is non-negative, the replacing will begin at the start'th offset into string.

If start is negative, the replacing will begin at the start'th character from the end of string.

PHP's documentation & syntax

mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )