[英]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
.结果应该是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.我尝试chunk_split()
和str_split()
,但它只从字符串的开头开始工作,而不是从最后一个开始工作。
simple use strrev()
and chunk_split()
简单使用strrev()
和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. 您需要使用strrev()
和chunk_split()
函数。
<?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. 函数strrev
会将字符串反转为1020109
,然后使用chunk_split()再次将其反转。
<?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.正则表达式允许在单个 function 调用中完成此操作,无需任何修剪。
Simply add a space at every position that is followed by an even number of characters.只需在每个 position 处添加一个空格,后跟偶数个字符。
Don't worry, you won't encounter an infinite loop -- the string is evaluated entirely before applying replacements.不用担心,您不会遇到无限循环——在应用替换之前完全评估字符串。
$str = 9010201;
var_export(
preg_replace(
'~.\K(?=(?:.{2})+$)~',
" ",
$str
)
);
Output: 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.如果模式是(?=.{2}+$)
,正则表达式引擎会错误地解释+
。 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. +
将明确要求{2}
量词必须使用“贪婪”/占有式匹配(尽可能不返回字符)——但这在这种情况下没有帮助或没有意图。 Demo of wrong behavior.错误行为的演示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.