开发者

regular expression search and replace

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 /> 

Plea开发者_如何学JAVAse help me


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


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.


For this specific case:

s/<br \/> 4/<hr \/> 4/


There is no need to use regexp.

echo str_replace(' <br /> 4', ' <hr /> 4', $str);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜