简体   繁体   中英

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.

simple use strrev() and chunk_split()

<?php

$str = 9010201;

echo trim(strrev(chunk_split(strrev($str),2, ' ')));

?>

Use this code:

You need to use strrev() and chunk_split() function.

<?php
$str = 9010201;
$rev = strrev($str);
$split = trim(chunk_split($rev, 2, ' '));
echo strrev($split); //9 01 02 01
?>

Function strrev will reverse the string to 1020109 , then use chunk_split() and reverse it again.

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

Regex allows this to be done in a single function call without any trimming.

Simply add a space at every position that is followed by an even number of characters.

Don't worry, you won't encounter an infinite loop -- the string is evaluated entirely before applying replacements.

Code: ( Demo )

$str = 9010201;

var_export(
    preg_replace(
        '~.\K(?=(?:.{2})+$)~',
        " ",
        $str
    )
);

Output:

'9 01 02 01'

Pattern breakdown:

.          #match any character
\K         #do not consume previously matched character
(?=        #lookahead (consume no characters)
  (?:      #encapsulate expression logic without capturing
    .{2}   #match any two characters
  )+       #require one or more of the expression
  $        #match the end of the string
)          #end of lookahead

The effect of the pattern on the provided string adds a space just before the sixth-from-the-end, fourth-from-the-end, and second-from-the-end characters.

If the pattern was (?=.{2}+$) , the regex engine would interpret the + incorrectly. The + would explicitly demand that the {2} quantifier must use "greedy"/possessive matching (not give back characters when possible) -- but that is not helpful or intended in this case. Demo of wrong behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM