替换指定的子字符串出现次数

时间:2014-10-29 07:02:25

标签: php regex

我想替换这样的指定子字符串出现:

<?php
/**
 * $str string the query string
 * $char string Check character
 * $arr  array() return arr
 */
$str = "<p><img src='/upload/20141015/20141015171814_85552.jpg' style='float:none;' alt='' /></p>
<p><img src='/upload/20141015/20141015171814_61056.jpg' style='float:none;' alt='' /></p>
<p><img src='/upload/20141015/20141015171815_89502.jpg' style='float:none;' alt='' /></p>
<p><img src='/upload/20141015/20141015171816_66873.jpg' style='float:none;' alt='' /></p>
<p><img src='/upload/20141015/20141015171817_62646.jpg' style='float:none;' alt='' /></p>
<p><img src='/upload/20141015/20141015171817_67373.jpg' style='float:none;' alt='' /></p>
<p><img src='/upload/20141015/20141015171820_87577.jpg' style='float:none;' alt='' /></p>";
       $j = 0;
       $arr = array();
       $count = substr_count($str, "</p>");
       for($i = 0; $i < $count; $i++){
             $j = strpos($str, "</p>", $j);
             $arr[] = $j;
             $j = $j+1;
       echo substr_replace($str,'[!--page--]',$arr[$i]);
       }
?>

我想输出的结果应该是:

<p><img src="/upload/20141015/20141015171814_85552.jpg" style="float:none;" alt="" /></p>
<p><img src="/upload/20141015/20141015171814_61056.jpg" style="float:none;" alt="" /></p>
<p><img src="/upload/20141015/20141015171815_89502.jpg" style="float:none;" alt="" /></p>
[!--page--]
<p><img src="/upload/20141015/20141015171816_66873.jpg" style="float:none;" alt="" /></p>
<p><img src="/upload/20141015/20141015171817_62646.jpg" style="float:none;" alt="" /></p>
<p><img src="/upload/20141015/20141015171817_67373.jpg" style="float:none;" alt="" /></p>
[!--page--]
<p><img src="/upload/20141015/20141015171818_18695.jpg" style="float:none;" alt="" /></p>
<p><img src="/upload/20141015/20141015171818_27048.jpg" style="float:none;" alt="" /></p>
<p><img src="/upload/20141015/20141015171819_47298.jpg" style="float:none;" alt="" /></p>
[!--page--]
<p><img src="/upload/20141015/20141015171820_87577.jpg" style="float:none;" alt="" /></p>

但结果并非如此,你可以帮助如何纠正它?谢谢。

1 个答案:

答案 0 :(得分:0)

echo preg_replace('/((.*\n){3})/m',"\\1[!--page--]\n",$str);

$i=1;
$lines = preg_split('/<\/p>/',$str,0,PREG_SPLIT_NO_EMPTY);
foreach ($lines as $line){
echo $line.'</p>';
if($i%3===0) echo "\n".'[!--page--]';
$i++;
}