每 4 个字符后添加空格


Add space after every 4th character

我想在每 4 个字符之后到字符串末尾的一些输出中添加一个空格。我试过了:

$str = $rows['value'];
<? echo substr($str, 0, 4) . ' ' . substr($str, 4); ?>

这让我在前 4 个字符之后获得了空格。

如何让它在每 4 日之后显示一次?

您可以使用chunk_split [docs]

$str = chunk_split($rows['value'], 4, ' ');

演示

如果字符串的长度是 4 的倍数,但您不想要尾随空格,则可以将结果传递给 trim

Wordwrap 完全符合您的要求:

echo wordwrap('12345678' , 4 , ' ' , true )

将输出:1234 5678

例如,如果您想在每第二个数字之后使用一个连字符,请将"4"换成"2",将空格换成连字符:

echo wordwrap('1234567890' , 2 , '-' , true )

将输出:12-34-56-78-90

参考 - 自动换行

你已经见过这个叫做自动换行的函数吗?http://us2.php.net/manual/en/function.wordwrap.php

这是一个解决方案。像这样开箱即用。

<?php
$text = "Thiswordissoverylong.";
$newtext = wordwrap($text, 4, "'n", true);
echo "$newtext'n";
?>

这是一个字符串的示例,长度不是 4 的倍数(在我的例子中是 5(。

function space($str, $step, $reverse = false) {
    
    if ($reverse)
        return strrev(chunk_split(strrev($str), $step, ' '));
    
    return chunk_split($str, $step, ' ');
}

用:

echo space("0000000152748541695882", 5);

结果: 00000 00152 74854 16958 82

反向模式使用(瑞士账单的"BVR代码"(:

echo space("1400360152748541695882", 5, true);

结果:14 00360 15274 85416 95882

编辑2021-02-09

对于EAN13条形码格式化也很有用:

space("7640187670868", 6, true);

结果 : 7 640187 670868

简短语法版本:

function space($s=false,$t=0,$r=false){return(!$s)?false:(($r)?trim(strrev(chunk_split(strrev($s),$t,' '))):trim(chunk_split($s,$t,' ')));}

希望它能帮助你们中的一些人。

方法是拆分为 4 个字符的块,然后再次将它们连接在一起,每个部分之间都有一个空格。

由于如果最后一个块正好有 4 个字符,这在技术上会错过在最后插入一个,我们需要手动添加那个(演示(:

$chunk_length = 4;
$chunks = str_split($str, $chunk_length);
$last = end($chunks);
if (strlen($last) === $chunk_length) {
    $chunks[] = '';
}
$str_with_spaces = implode(' ', $chunks);

行:

$yourstring = "1234567890";
echo implode(" ", str_split($yourstring, 4))." ";

这应该给你作为输出:
1234 5678 90

这就是全部:D

该函数wordwrap()基本上执行相同的操作,但是这也应该有效。

$newstr = '';
$len = strlen($str); 
for($i = 0; $i < $len; $i++) {
    $newstr.= $str[$i];
    if (($i+1) % 4 == 0) {
        $newstr.= ' ';
    }
}

PHP3 兼容:

试试这个:

$strLen = strlen( $str );
for($i = 0; $i < $strLen; $i += 4){
  echo substr($str, $i, 4) . ' ';
} 
unset( $strLen );
StringBuilder str = new StringBuilder("ABCDEFGHIJKLMNOP");
int idx = str.length() - 4;
while (idx > 0){
  str.insert(idx, " ");
  idx = idx - 4;
}
return str.toString();

说明,此代码将从右到左添加空格:

 str = "ABCDEFGH" int idx = total length - 4; //8-4=4
    while (4>0){
        str.insert(idx, " "); //this will insert space at 4th position
        idx = idx - 4; // then decrement 4-4=0 and run loop again
    }

最终输出将是:

ABCD EFGH