2017-06-12 8 views

答えて

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

nを相殺して、str_replace()に結果を渡した後、あなたは、文字列の残りの部分を取得するためにsubstr()を使用することができます。

$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; 

には、あなたが探しているものが含まれています。

+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

以下の私の関数を参照してください。したがって、3番目のパラメータを、指定された位置の後に最初に現れる「次の」位置に設定する必要があります。これを行うには、$ position = strpos($ a、 "next"、$ position);を使用します。

substr_replace関数の4番目のパラメータは、置換する文字数を使用します。これを文字列 "next"の文字数に設定できます。次に、「次へ」のn番目の置換を置き換える必要があります。最終的なコードは次のようになります:

$replaced_string = substr_replace($a, $replacement, strpos($a, "next", $position), strlen("next")); 
関連する問題