2017-06-12 148 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")); 
相關問題