php替换第n个位置出现的第一个字符串

php替换第n个位置出现的第一个字符串,php,Php,我有字符串: $a="some some next some next some some next"; 我想删除从位置n开始出现的一个“next” substr\u replace可以设置偏移量,但在设置偏移量之后会获取所有内容,这是错误的 preg_replace无法从偏移开始,这也是错误的 如何做到这一点?使用以下代码: <?php $a="some some next some next some some next"; $n = 0; $substring = 'next';

我有字符串:

$a="some some next some next some some next";
我想删除从位置n开始出现的一个“next”

substr\u replace
可以设置偏移量,但在设置偏移量之后会获取所有内容,这是错误的

preg_replace
无法从偏移开始,这也是错误的

如何做到这一点?

使用以下代码:

<?php
$a="some some next some next some some next";
$n = 0;
$substring = 'next';

$index = strpos($a,$substring);
$cut_string = '';
if($index !== false)
$cut_string = substr($a, $index + strlen($substring));

var_dump($cut_string);
?>

您可以使用
substr()
获取偏移量
n
后的字符串剩余部分,然后将结果传递给
stru replace()

$replacedStringAfterOffset
现在包含指定偏移之后的所有内容,因此现在必须将偏移之前(未更改)的零件与偏移之后(更改)的零件连接起来:

$newString
现在包含您要查找的内容。

请参阅下面的“我的功能”

<?php

echo $a="some some next some next some some next";


$cnt = 0;

function nthReplace($search, $replace, $subject, $n, $offset = 0) {
    global $cnt;  
    $pos = strpos($subject, $search , $offset); 
    if($cnt == $n){
        $subject = substr_replace($subject, $replace, $pos, strlen($search));

    } elseif($pos !== false){
        $cnt ++;
        $subject = nthReplace($search, $replace, $subject, $n, $offset+strlen($search));
    } 
    return $subject;
}

 echo  $res = nthReplace('next', '', $a,1); 

据我所知,给定位置是字符串中某个字符的位置。因此,您需要将第三个参数设置为给定位置后第一次出现“next”的位置。您可以使用:$position=strpos($a,“next”,$position)来实现这一点

substr_replace函数的第4个参数采用要替换的字符数。您可以将其设置为字符串“next”中的字符数。然后,它应该替换第n次出现的“next”。最终代码可以如下所示:

$replaced_string = substr_replace($a, $replacement, strpos($a, "next", $position), strlen("next"));

str_replace函数中的1不是要替换的数量,而是返回的已替换数量。所以在那个地方需要可变,所以这个解决方案不起作用。
<?php

echo $a="some some next some next some some next";


$cnt = 0;

function nthReplace($search, $replace, $subject, $n, $offset = 0) {
    global $cnt;  
    $pos = strpos($subject, $search , $offset); 
    if($cnt == $n){
        $subject = substr_replace($subject, $replace, $pos, strlen($search));

    } elseif($pos !== false){
        $cnt ++;
        $subject = nthReplace($search, $replace, $subject, $n, $offset+strlen($search));
    } 
    return $subject;
}

 echo  $res = nthReplace('next', '', $a,1); 
$replaced_string = substr_replace($a, $replacement, strpos($a, "next", $position), strlen("next"));