2017-06-12 190 views
0

我有串:PHP替换字符串中第一次出现的第n个位置

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

,我想删除的“下一步”一个出现在首发位置ñ

substr_replace可以设置偏移量,但后面的一切都是错误的。

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

这怎么办?

回答

0

使用此代码:

<?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); 
?> 
0

您可以使用substr()得到抵消n后的字符串的其余部分,然后将结果传递给str_replace()

$input = 'some some some next next some some next some.'; 
$offset = 5; // Example offset 
$toBeReplaced = 'next'; 
$replacement = ''; // Empty string as you want to remove the occurence 
$replacedStringAfterOffset = str_replace($toBeReplaced, $replacement, substr($input, $offset), 1); // The 1 indicates there should only one result be replaced 

$replacedStringAfterOffset后,现在包含一切你指定偏移量,所以现在必须将偏移量之前(未更改)的部分与偏移量(更改后)之后的部分连接起来:

$before = substr($input, 0, $offset - 1); 
$after = $replacedStringAfterOffset; 
$newString = $before . $after; 

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

+0

str_replace函数中的1不是要替换的数量,而是返回的替换次数。 所以在那个地方需要变量,因此这个解决方案不起作用。 –

0

见下

<?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); 
0

我的函数按我的理解给定的位置在字符串中的一些字符的位置。因此,您需要将第三个参数设置为给定位置后第一个出现“next”的位置。你可以这样做:$ position = strpos($ a,“next”,$ position);

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

$replaced_string = substr_replace($a, $replacement, strpos($a, "next", $position), strlen("next")); 
相关问题