[英]PHP Replace the Nth occurrence of char in a string with substring
[英]php replace first occurrence of string from nth position
我有字符串:
$a="some some next some next some some next";
starting on position . 并且我想删除从位置开始的事件的出现。
substr_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
之后的其余字符串,然后将结果传递给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
现在包含您要查找的内容。
请参阅下面的功能
<?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);
据我了解,给定位置是字符串中某个字符的位置。 因此,您需要将第3个参数设置为在给定位置之后首次出现“ next”的位置。 您可以使用以下方法执行此操作:$ position = strpos($ a,“ next”,$ position);
substr_replace函数的第4个参数采用要替换的字符数。 您可以将其设置为字符串“ next”中的字符数。 然后应替换第n个出现的“ next”。 最终代码如下所示:
$replaced_string = substr_replace($a, $replacement, strpos($a, "next", $position), strlen("next"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.