phpstringswapcpu-wordword-boundary

Swap first two letters of every word in string


I have a string:

Hello, How Are You.

I want this output:

eHllo, oHw rAe oYu.

It doesn't matter whether there are any special characters, I just want to reverse the first two letters in every word.


Solution

  • You can use preg_replace_callback like as

    $str = "Hello, How Are You.";
    echo preg_replace_callback("/([a-z]+)/i",function($m){
        return implode(array_map('strrev',str_split($m[0],2)));
    },$str);
    

    Output:

    eHllo, oHw rAe oYu.
    

    Demo