Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/271.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 替换从2号开始的字符串_Php_Regex - Fatal编程技术网

Php 替换从2号开始的字符串

Php 替换从2号开始的字符串,php,regex,Php,Regex,如何替换字符串,使用普通替换或正则表达式仅替换找到的第二个结果 <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"></d

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

<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

代码
原子吸收光谱
党卫军
第二个fb根分区到最后一个应被删除


提前感谢您的帮助。

可能有更好的方法,但是为什么不在第一个位置使用占位符,替换其余位置,然后将占位符更改回原来的位置呢

$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);
$full\u text=文件获取内容($filename);
$text_to_replace='';
$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
的第一次调用中的第四个参数,它告诉函数只替换搜索文本的一个实例。它将仅用占位符替换第一个实例,然后第二个调用将删除所有剩余实例,第三个调用将用原始文本替换占位符。

尝试以下操作:

$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);
$str='STRING HERE';
$result=preg_replace_回调('@',function(){
静态$count=0;
如果(++$count>1){
返回null;
}否则{
$args=func\u get\u arg(0);
返回$args[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
$str=“…”;
$needle='';
$len=strlen($needle);
$pos=strpos($str,$needle)+$len;//跳过第一次发生
while(($pos=strpos($str,$needle,$pos))!==false)
$str=substr($str,0,$pos)。substr($str,$pos+len);//取下针头

首先不要将它包含在页面上是的,我不希望它有3个div。但是这个项目有4个原因,不幸的是我不能改变。谢谢,是的,这是可能的。但是3的更换可能会慢一点。让我们等待其他建议。当然,这是你的决定,但这听起来像是过早的优化。对任何大小合理的文件执行几次替换只需几微秒。+1,是的,您的答案就是我通常使用的答案。我不是为了这个而优化的,我只是想回忆一下做这类事情的另一个正则表达式技巧。我记得以前有一些正则表达式修饰符/技巧可以在这种情况下使用,看看这个