繁体   English   中英

在每第 4 个字符后添加空格

[英]Add space after every 4th character

我想在每第 4 个字符之后向某些输出添加一个空格,直到字符串末尾。 我试过:

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

这让我在前 4 个字符之后有了空间。

我怎样才能让它每 4 次显示一次?

您可以使用chunk_split [文档]

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

演示

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

Wordwrap 完全符合您的要求:

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

将输出:1234 5678

例如,如果你想在第二个数字后加一个连字符,将“4”换成“2”,并将空格换成连字符:

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

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

参考 - wordwrap

你见过这个叫做 wordwrap 的函数吗? 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 个字符,这在技术上会错过在最后插入一个字符的机会,因此我们需要手动添加该字符( Demo ):

$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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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