PHP inserting some text before and after a string

2019-05-28 17:16发布

问题:

I'm pretty new to PHP and have a String which contains an HTML page. I'd need to insert some custom code BEFORE and AFTER any HR HTML tag. Example:

    <html>
    ....
     <p>INSERT HERE</p> 
     <hr class="pagebreak">
     <p>INSERT HERE</p> 

     <p>INSERT HERE</p> 
     <hr class="pagebreak">
     <p>INSERT HERE</p> 
    ....
    </html>

I've tried with several combinations of preg_replace and substr_replace, however I still couldn't manage to insert the custom code in all places I need. Anybody can help me to solve this puzzle ? P.s. I need to use PHP standard String functions- I cannot use any HTML parsing library since I don't have control over the PHP libraries available on the server. Thanks a lot Linda

回答1:

All you need to get is good regular expression, assuming that you managed to get it work at least partially, you propably had bad expression (example would help). I tested this code for you and it should work on all your <hr>s:

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

variable oldtext is what you had before, new text is what you want, and prefix and suffix is what you want to add around hr tag



回答2:

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

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