views:

53

answers:

5

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

A: 

For this specific case:

s/<br \/> 4/<hr \/> 4/
king_nak
Hello ,i had edit my code
Thoman
+1  A: 

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.

Amarghosh
Hello ,i had edit my code
Thoman
A: 

There is no need to use regexp.

echo str_replace(' <br /> 4', ' <hr /> 4', $str);
Anpher
A: 

Sorry all , I want fourth position or other position of object

Thoman
+1  A: 

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
polygenelubricants
Thanks for reply But I want replace only one position .
Thoman
@Thoman: `preg_replace` has a `limit` argument; just set it to `1` (http://ideone.com/HKpjj)
polygenelubricants
Great Thank for help
Thoman