Changing letters in words in php but not all of the same letter

huangapple go评论60阅读模式
英文:

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.

&lt;?php

  $str  = &quot;kak kaka&quot;;
 
  $searchVal = array(&quot;a&quot;);
 
  $replaceVal = array(&quot;o&quot;);
  
  $res = str_replace($searchVal, $replaceVal, $str);
  print_r($res);
?&gt;

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:

&lt;?php
$s = &quot;kak kaak kaka kaaka&quot;;
$result = [];
foreach( explode(&#39; &#39;, $s) as $word )
{
    if( substr($word,-1) == &#39;a&#39; )
        $word = str_replace(&#39;a&#39;,&#39;o&#39;,$word);
    $result[] = $word;
}
$result = implode(&#39; &#39;, $result);
echo &quot;$result\n&quot;;
?&gt;

Output:

kak kaak koko kooko

答案2

得分: 0

你没有添加任何逻辑来检查最后一个字符的有效性。为此,您可以使用 preg_replace_callback 一行解决方案,匹配和仅“过滤”那些以 a 结尾的单词,然后使用 str_replace 替换所有 ao

片段:

<?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:

&lt;?php

echo preg_replace_callback(&#39;/\b[^\s]*a\b/i&#39;, fn($matches) =&gt; str_replace(&quot;a&quot;, &quot;o&quot;, $matches[0]), &#39;kak kaka aaak aaa&#39;);

Online Demo

huangapple
  • 本文由 发表于 2023年5月17日 13:07:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76268729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定