3

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

0

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, both your solution and and inhan workerd perfectly. Sorry I have just built my profile so I cannot add you any score for your reply :-(
No problem, at least you got solution, just notice the difference, my expression works even if <hr> takes multiple lines, however it is case sensitive so it wont work for <HR>, if you want to change it, just put #i at the end instead
2
$before = '<p>Before the hr tag</p>';
$after = '<p>After the hr tag</p>';

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

1 Comment

Thank you also for your great suggestion inhan !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.