英文:
Changing letters in words in php but not all of the same letter
问题
我想要将单词中的字母a改为o,但不是所有的字母a,在我的规则中,只有在单词以a结尾的情况下,才会将字母a改为o,但所有的字母a都变成了字母o,kak kok。kaka koko正在发生。kak不以a结尾,但中间的字母a也变成了字母o。我需要kak kak状态变成下面的kaka koko状态。
<?php
$str = "kak kaka";
$searchVal = array("a");
$replaceVal = array("o");
$res = str_replace($searchVal, $replaceVal, $str);
print_r($res);
?>
英文:
I want to change the letter a in the word to o, but not all the letter a, in my rule, only the letters a in the words ending with a should be changed to o, but all the letters a are changing to the letter o, kak kok . kaka koko is happening. kak does not end with a, but the letter a in the middle is changing to the letter o. I need the kak kak state to be in the kaka koko state below.
<?php
$str = "kak kaka";
$searchVal = array("a");
$replaceVal = array("o");
$res = str_replace($searchVal, $replaceVal, $str);
print_r($res);
?>
I didn't know what to try.
答案1
得分: 1
这是您提供的代码的翻译结果:
<?php
$s = "kak kaak kaka kaaka";
$result = [];
foreach( explode(' ', $s) as $word )
{
if( substr($word,-1) == 'a' )
$word = str_replace('a','o',$word);
$result[] = $word;
}
$result = implode(' ', $result);
echo "$result\n";
?>
输出:
kak kaak koko kooko
如果您需要进一步的翻译或帮助,请随时提问。
英文:
If my assumption in the comments was correct, this will do it:
<?php
$s = "kak kaak kaka kaaka";
$result = [];
foreach( explode(' ', $s) as $word )
{
if( substr($word,-1) == 'a' )
$word = str_replace('a','o',$word);
$result[] = $word;
}
$result = implode(' ', $result);
echo "$result\n";
?>
Output:
kak kaak koko kooko
答案2
得分: 0
你没有添加任何逻辑来检查最后一个字符的有效性。为此,您可以使用 preg_replace_callback
一行解决方案,匹配和仅“过滤”那些以 a
结尾的单词,然后使用 str_replace
替换所有 a
为 o
。
片段:
<?php
echo preg_replace_callback('/\b[^\s]*a\b/i', fn($matches) => str_replace("a", "o", $matches[0]), 'kak kaka aaak aaa');
英文:
You haven't added any logic to check for last character validation. For this, you can use preg_replace_callback
one line solution to match and filter only those words that end with a
and then use str_replace
to replace all a
with o
.
Snippet:
<?php
echo preg_replace_callback('/\b[^\s]*a\b/i', fn($matches) => str_replace("a", "o", $matches[0]), 'kak kaka aaak aaa');
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论