簡體   English   中英

PHP從第n個位置替換字符串的第一次出現

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM