如何从每个单词的某个位置开始替换字符串中每个单词的字符?
例如:
$string = "one twone trone fourone nourone";<br />
// I want to replace each n with X starting from second position in each word.<br />
// Last word has n on first position and should remain there.<br />
$new_string = "oXe twoXe troXe fouroXe nouroXe";
答案 0 :(得分:2)
目前尚不清楚首先考虑的是n
。一种可能的方法:
$string = "one twone trone fourone nourone";
$new_string = preg_replace('/\Bn/', 'X', $string);
// string(31) "oXe twoXe troXe fouroXe nouroXe";
Demo。如您所见,使用了正则表达式替换函数(preg_replace);模式/\Bn
被描述为“匹配所有n
符号,前面没有单词边界”(='不在单词的开头'。)
答案 1 :(得分:0)
我设法解决了这个问题。也许不是最好的方法,但它运作正常:
$ string ='ĂĂĂononĂnonĂĂnĂĂ';
$ string = explode('',$ string);
$ string_output =“”;
foreach($ string as $ s){
$ first_letter = substr($ s,0,1);
$ remaining_letters = substr($ s,1,25);
$ remaining_letters = str_replace(“Ă”,“ă”,$ remaining_letters);
$ s = $ first_letter。$ remaining_letters;
$ string_output。= $ s。“”;
}
$ string = $ string_output;