skip to Main Content

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);
?>
type here

I didn’t know what to try.

2

Answers


  1. 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 "$resultn";
    ?>
    

    Output:

    kak kaak koko kooko
    
    Login or Signup to reply.
  2. 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]*ab/i', fn($matches) => str_replace("a", "o", $matches[0]), 'kak kaka aaak aaa');
    

    Online Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search