How can I insert text before and after a string in PHP?

Solution:1

The key is to use the correct regular expression. If your previous attempt didn’t work properly, it was likely due to an incorrect pattern (sharing your attempt would help). I tested the following code, and it should work for all your


tags:


$newtext = preg_replace(
    "#(<hr[^>]*>)#s",
    $yourprefix . "$1" . $yoursuffix,
    $oldtext
);

$oldtext → your original string.

$newtext → the updated string after replacements.

$yourprefix / $yoursuffix → the text or HTML you want to add before and after each


tag.

Solution:2
Another way is to wrap the


tag with custom content using preg_replace:


$before = '<p>Before the hr tag</p>';
$after  = '<p>After the hr tag</p>';

$str = preg_replace(
    '/(<hr(.*?)>)/i',
    $before . '$1' . $after,
    $str
);

$before → content to insert before the


tag.

$after → content to insert after the


tag.

$str → the original text that contains


tags.

This way, every


in your text will be wrapped with the specified content.