Hello This is some code
<br /> <br /> <br /> <br /> <br /> <br />
but
I want replace
<br /> fourth with <hr />
And this output
<br /> <br /> <br /> <hr /> <br /> <br />
Please help me
Hello This is some code
<br /> <br /> <br /> <br /> <br /> <br />
but
I want replace
<br /> fourth with <hr />
And this output
<br /> <br /> <br /> <hr /> <br /> <br />
Please help me
This will work only for the given case:
preg_replace("#<br /> 4#", "<hr /> 4", $str);
If you're looking for a generic solution, RegEx is not the best tool for that. Use HTML/XML parser.
There is no need to use regexp.
echo str_replace(' <br /> 4', ' <hr /> 4', $str);
Perhaps something like this is what you want:
<?php
$text = <<<EOT
<br /> 1 <br /> 2 <br /> 3 <br /> 4 <br /> 5 <br /> 6
<br /> 7 <br /> 8 <br /> 9 <br /> 10 <br /> 11 <br /> 12
<br /> 13 <br /> 14 <br /> 15 <br /> 16 <br /> 17 <br /> 18
EOT;
$tag = '<br \\/>';
$content = '[^<]*';
print preg_replace("/($content(?:$tag$content){3})$tag/", '$1<BREAK! />', $text);
?>
The output (as seen on ideone.com):
<br /> 1 <br /> 2 <br /> 3 <BREAK! /> 4 <br /> 5 <br /> 6
<br /> 7 <BREAK! /> 8 <br /> 9 <br /> 10 <br /> 11 <BREAK! /> 12
<br /> 13 <br /> 14 <br /> 15 <BREAK! /> 16 <br /> 17 <br /> 18
That said, this is a pain and you really shouldn't be using regex for this.
If you only want to do one replacement, you can set the limit
argument to preg_replace
:
preg_replace("/($content(?:$tag$content){3})$tag/", '$1<BREAK! />', $text, 1);
^^limit