繁体   English   中英

PHP 将字符串中第 N 次出现的 char 替换为 substring

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM