Replace nth occurence
Posted: Wed Sep 10, 2008 11:09 am
Hi
I want to replace the 4th pattern only in a preg_replace.
This has nothing to with XML, so Im not looking for a DOM solution - just wanted to give a good example string
Is there a better solution ?
Thanks
I want to replace the 4th pattern only in a preg_replace.
This has nothing to with XML, so Im not looking for a DOM solution - just wanted to give a good example string
Code: Select all
<?php
$xml = "
<starttag>
<starttag>content 1</endtag>
<starttag>content 2</endtag>
<starttag>content 3</endtag>
<starttag>content 4</endtag>
<starttag>content 5</endtag>
</endtag>
";
$pattern = '#((.*?<starttag>.*?</endtag>.*?){3})(<starttag>.*?</endtag>)#is';
$xml = preg_replace($pattern, '$1<starttag>content changed</endtag>', $xml, 1);
echo $xml;Code: Select all
php preg_replace.php
<starttag>
<starttag>content 1</endtag>
<starttag>content 2</endtag>
<starttag>content 3</endtag>
<starttag>content changed</endtag>
<starttag>content 5</endtag>
</endtag>Thanks