简体   繁体   中英

php replace first occurrence of string from nth position

I have string:

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

and I would like to remove one occurrence of 'next' starting on position n .

substr_replace can set offset, but takes everything after that, which is wrong.

preg_replace cannot start at the offset, which is also wrong.

How can this be done?

Use this code:

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

You can use substr() to get the rest of the string after offset n and then pass the result to 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 now contains everything after your specified offset, so now you have to connect the part from before the offset (not changed) with the part after the offset (changed):

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

$newString now contains what you are looking for.

See my function below

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

As I understand the given position is the position of some character in your string. So you need to set the 3rd parameter to the position of first occurrence of "next" after the given position. You can do this using: $position = strpos($a, "next", $position);

The 4th parameter of the substr_replace function takes the number of characters to replace. You can set this to the number of characters in the string "next". It should then replace the nth occurrence of "next". The final code can look like following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM