から文字列の最初の出現を交換してください。PHPは、私は、文字列を持っているn番目の位置
substr_replace
はオフセットを設定できますが、それ以降はすべてが間違っています。
preg_replace
オフセットで開始できません。これも間違っています。
どうすればいいですか?
から文字列の最初の出現を交換してください。PHPは、私は、文字列を持っているn番目の位置
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);
?>
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;
には、あなたが探しているものが含まれています。
私は与えられた位置は、あなたの文字列の一部の文字の位置であることを理解したよう
<?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番目のパラメータを、指定された位置の後に最初に現れる「次の」位置に設定する必要があります。これを行うには、$ position = strpos($ a、 "next"、$ position);を使用します。
substr_replace関数の4番目のパラメータは、置換する文字数を使用します。これを文字列 "next"の文字数に設定できます。次に、「次へ」のn番目の置換を置き換える必要があります。最終的なコードは次のようになります:
$replaced_string = substr_replace($a, $replacement, strpos($a, "next", $position), strlen("next"));
str_replace関数の1は、置き換えの数ではなく、置き換えられた数を返します。 その場所で変数を変更する必要があるため、この解決策は機能しません。 –