Search code examples
phpstringdelimiterspacing

Add a space between every 2 characters starting from the end of a string


I want to add space before every two characters from the end of the string.

$str = 9010201;

The result should be 9 01 02 01.

I tried chunk_split() and str_split(), but it worked only from the beginning of the string but not from the last.


Solution

  • simple use strrev() and chunk_split()

    <?php
    
    $str = 9010201;
    
    echo trim(strrev(chunk_split(strrev($str),2, ' ')));
    
    ?>