【问题标题】:Replace a string starting on 2nd替换从 2 开始的字符串
【发布时间】:2013-01-13 08:25:56
【问题描述】:

如何替换字符串,使用普通替换或正则表达式仅替换第二个找到的结果

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

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

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

预期结果应该是

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


aas
ss

应该删除第 2 个 fb-root div,直到最后一个。

提前感谢您的帮助。

【问题讨论】:

  • 首先不要在页面上包含它
  • 是的,我不希望它有 3 个 div。但是这个项目有4个是有原因的,不幸的是我不能改变。

标签: php regex


【解决方案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时的第四个参数,它告诉函数只替换搜索文本的一个实例。它将仅将第一个实例替换为占位符,然后第二次调用将删除所有剩余实例,第三次调用将占位符替换为原始文本。

【讨论】:

  • 谢谢,是的,这是可能的。但是 3 替换可能会慢一些。让我们等待其他建议。
  • 当然,这是您的决定,但这听起来像是过早的优化。对任何大小合理的文件执行几次替换只需几微秒。
  • +1,是的,你的答案是我通常使用的。我不只是为此进行优化,只是想回忆一下其他正则表达式技巧来做这种事情。
【解决方案2】:

试试这个:

$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);

【讨论】:

【解决方案3】:

你可以这样做:

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 1970-01-01
    • 2016-02-06
    • 2020-08-08
    • 2016-08-03
    • 2016-09-15
    相关资源
    最近更新 更多