[英]PHP Replace the Nth occurrence of char in a string with substring
我試圖弄清楚如何完成以下工作。 基本上,我想做一個 str_replace() 但只在第 N 次出現。 有任何想法嗎?
//Inputs
$originalString = "Hello world, what do you think of today's weather";
$findString = ' ';
$nthOccurrence = 8;
$newWord = ' beautiful ';
//Desired Output
Hello world, what do you think of today's beautiful weather
謝謝你的幫助。
我在這里找到了答案 - https://gist.github.com/VijayaSankarN/0d180a09130424f3af97b17d276b72bd
$subject = "Hello world, what do you think of today's weather";
$search = ' ';
$occurrence = 8;
$replace = ' nasty ';
/**
* String replace nth occurrence
*
* @param type $search Search string
* @param type $replace Replace string
* @param type $subject Source string
* @param type $occurrence Nth occurrence
* @return type Replaced string
*/
function str_replace_n($search, $replace, $subject, $occurrence)
{
$search = preg_quote($search);
echo preg_replace("/^((?:(?:.*?$search){".--$occurrence."}.*?))$search/", "$1$replace", $subject);
}
str_replace_n($search, $replace, $subject, $occurrence);
$originalString = "Hello world, what do you think of today's weather";
$findString = ' ';
$nthOccurrence = 8;
$newWord = ' beautiful ';
$array = str_split($originalString);
$count = 0;
$num = 0;
foreach ($array as $char) {
if($findString == $char){
$count++;
}
$num++;
if($count == $nthOccurrence){
array_splice( $array, $num, 0, $newWord );
break;
}
}
$newString = '';
foreach ($array as $char) {
$newString .= $char;
}
echo $newString;
我會考慮這樣的事情:
function replaceNth($string, $substring, $replacement, $nth = 1){
$a = explode($substring, $string); $n = $nth-1;
for($i=0,$l=count($a)-1; $i<$l; $i++){
$a[$i] .= $i === $n ? $replacement : $substring;
}
return join('', $a);
}
$originalString = 'Hello world, what do you think of today\'s weather';
$test = replaceNth($originalString, ' ', ' beautiful ' , 8);
$test2 = replaceNth($originalString, 'today\'s', 'good');
這是一個帶有\K
的緊湊的小正則表達式,它允許您替換第 n 次出現的字符串,而無需在模式中重復針。 如果您的搜索字符串是動態的並且可能包含具有特殊含義的字符,那么preg_quote()
對模式的完整性至關重要。
如果您想將搜索字符串和第 n 次出現靜態寫入您的模式,它可能是:
(?:.*?\K ){8}
(?:[^ ]*\K ){8}
\K
告訴正則表達式模式“忘記”全字符串匹配中任何先前匹配的字符。 換句話說,“重新啟動全字符串匹配”或“從這里保持”。 在這種情況下,模式只保留第 8 個空格字符。
代碼:(演示)
function replaceNth(string $input, string $find, string $replacement, int $nth = 1): string {
$pattern = '/(?:.*?\K' . preg_quote($find, '/') . '){' . $nth . '}/';
return preg_replace($pattern, $replacement, $input, 1);
}
echo replaceNth($originalString, $findString, $newWord, $nthOccurrence);
// Hello world, what do you think of today's beautiful weather
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.