PHP: Insert HTML after the nth occurrence of a tag [duplicate]

PHP: Insert HTML after the nth occurrence of a </p> tag [duplicate]



This question already has an answer here:



I am trying to inject some html after the nth </p> tag in HTML I retrieve from my database.


</p>



I have found this php code that works for regular text, but does not appear to work for </p>.


</p>


function str_replace_n($search, $replace, $subject, $occurrence)
$search = preg_quote($search,'/');

return preg_replace("/^((?:(?:.*?$search)".--$occurrence.".*?))$search/", "$1$replace", $subject);



Been trying to get this to work, but have been unable to do so.



I am calling the function using the following call:


$row['post_content'] = $this->str_replace_n("</p>", "<a href='https://www.google.com/'>test</a></p>",$this->test_html() , 2);



The html being returned by test_html() is:


<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis mattis in dolor at sodales. Donec nec pellentesque ipsum. Nullam a velit in neque volutpat rhoncus t
incidunt nec nisl. Suspendisse sem enim, tincidunt ac orci vel, sodales gravida metus. Duis dignissim urna ac porttitor imperdiet. Morbi in cursus nisl, vitae molest
ie ipsum. Suspendisse non ipsum suscipit, congue mauris ac, condimentum magna. Vivamus ultricies suscipit magna, sed finibus justo vestibulum sed.</p>

<p>Duis varius ultrices diam eu facilisis. Aenean non auctor nibh, vel blandit enim. Maecenas porta tellus at purus efficitur rutrum. Proin ullamcorper metus semper
tempus consectetur. Nullam vel pellentesque elit. Praesent fringilla libero elit, non blandit purus placerat eget. Nunc eu urna a est pretium convallis ac eget nunc.
Duis laoreet turpis sed sapien molestie, in ornare est lobortis.</p>

<p>Donec scelerisque consequat facilisis. Vestibulum at dignissim neque. Aenean tincidunt nulla in eros aliquet mollis. Fusce lacinia vehicula aliquet. Pellentesque
vitae orci eget purus suscipit suscipit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Vestibulum auctor, augue at vest
ibulum placerat, risus lacus sodales neque, non pretium leo velit vel est. Phasellus lacinia maximus eros, viverra finibus augue gravida pharetra. Integer id ferment
um ex.</p>

<p>Sed suscipit, massa ac laoreet auctor, justo ipsum congue sapien, at gravida nulla risus non erat. Donec varius vehicula velit, nec volutpat enim feugiat a. Sed t
empor finibus maximus. Sed mauris ipsum, dictum quis felis non, blandit sollicitudin purus. In a diam non sapien mattis cursus. In pharetra euismod finibus. Integer
placerat eu lorem in maximus.</p>

<p>Mauris ut dolor id lectus laoreet commodo. Integer venenatis blandit augue eget faucibus. Sed euismod dui mi, at congue turpis imperdiet ut. Proin vulputate ferme
ntum porttitor. Nulla facilisi. Mauris sollicitudin lectus elit, id ultricies ipsum vulputate nec. Maecenas interdum, arcu sit amet facilisis consequat, turpis liber
o blandit dolor, sed suscipit leo felis quis felis. Curabitur varius quam at leo dapibus suscipit.</p>



Any help would be greatly appreciated.



As for it being a duplicate question, I disagree. The linked to answer, while informative, does not provide any substantial information on how to do what I am trying to achieve.



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.






Processing html by means of regular expressions is a bad idea. That tool is not mighty enough for the task. INstead use a DOM parser like simpleDOM which is able to process and understand the actual structure of a markup document.

– arkascha
Sep 13 '18 at 4:36






Do youi have an example of how I can do it using a DOM parser? I tried doing that, but was not sure how to add text after a particular element.

– John Tangale
Sep 13 '18 at 12:19






As the duplicate question response, the indicated topic does not provide an example of how to solve this at all. There are much better answers to link to, but unfortunately those did not help either.

– John Tangale
Sep 13 '18 at 12:20




1 Answer
1



You have a couple of issues with your regexp. Firstly, you have anchored the regex to the start of the string with ^, so you will get at most one match. Secondly, you need to supply the s modifier so that . can match newlines as well as whitespace. Try this version of your str_replace_n function:


^


s


.


str_replace_n


function str_replace_n($search, $replace, $subject, $occurrence)
$search = preg_quote($search,'/');
return preg_replace("/((?:(?:.*?$search)".--$occurrence.".*?))$search/s", "$1$replace", $subject);



Example operation:


$html= '<p>Lorem ipsum </p>
<p>Duis varius ultrices.</p>
<p>Donec scelerisque .</p>
<p>Sed suscipit, massa.</p>
<p>Mauris ut dolor id</p>';
echo str_replace_n("</p>", "<a href='https://www.google.com/'>test</a></p>",$html , 2);



Output:


<p>Lorem ipsum </p>
<p>Duis varius ultrices.<a href='https://www.google.com/'>test</a></p>
<p>Donec scelerisque .</p>
<p>Sed suscipit, massa.<a href='https://www.google.com/'>test</a></p>
<p>Mauris ut dolor id</p>



Your version of the function is also designed to insert the text before the nth occurrence of the string. If you want to insert the new text after the nth occurrence you will need to change the function to:


function str_replace_n_after($search, $replace, $subject, $occurrence)
$search = preg_quote($search,'/');
return preg_replace("/((?:.*?$search)".$occurrence.")/s", "$1$replace", $subject);

echo str_replace_n_after("</p>", "<a href='https://www.google.com/'>test</a>",$html , 2);



Output:


<p>Lorem ipsum </p>
<p>Duis varius ultrices.</p><a href='https://www.google.com/'>test</a>
<p>Donec scelerisque .</p>
<p>Sed suscipit, massa.</p><a href='https://www.google.com/'>test</a>
<p>Mauris ut dolor id</p>



Demo on rextester

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)