0

How can I replace a string, using normal replace or regular expression to replace only the 2nd found result onwards

<div id="fb-root"></div>
codes

<div id="fb-root"></div>

aas
<div id="fb-root"></div>
ss
<div id="fb-root"></div>

Expected results should be

<div id="fb-root"></div>
codes


aas
ss

the 2nd fb-root div upto the last should be removed.

Thanks in advance for the help.

4

3 回答 3

1

可能有更好的方法来做到这一点,但为什么不为第一个使用占位符,替换其余的,然后将占位符改回来呢?

$full_text = file_get_contents($filename);
$text_to_replace = '<div id="fb-root"></div>';
$placeholder = '__PLACEHOLDER__';

$full_text = str_replace($text_to_replace, $placeholder, $full_text, 1);
$full_text = str_replace($text_to_replace, '', $full_text);
$full_text = str_replace($placeholder, $text_to_replace, $full_text);

这里的关键是第一次调用中的第四个参数str_replace,它告诉函数只替换搜索文本的一个实例。它将仅用占位符替换第一个实例,然后第二次调用将删除所有剩余实例,第三次调用将用原始文本替换占位符。

于 2013-01-13T08:40:11.740 回答
1

尝试这个:

$str = 'STRING HERE';
$result = preg_replace_callback('@<div\s+id="fb-root"></div>@', function(){
    static $count = 0;
    if(++$count > 1){
        return null;
    }else{
        $args = func_get_arg(0);
        return $args[0];
    }
}, $str);
于 2013-01-13T08:43:01.223 回答
0

你可以这样做:

$str = "...";

$needle = '<div id="fb-root"></div>';
$len = strlen($needle);
$pos = strpos($str, $needle) + $len; // skip the first occurance
while (($pos = strpos($str, $needle, $pos)) !== false)
    $str = substr($str, 0, $pos) . substr($str, $pos + $len);// remove the needle
于 2013-01-13T09:13:01.217 回答