简体   繁体   English

在PHP中的for循环中分割8个字符的字符串

[英]split string of 8 characters in for loop in php

I have strings (checked with gettype) from 8 characters like this: 我有8个字符组成的字符串(用gettype检查):

47780000
79110000
96040000
49321200

My goal is to split each string in 4 parts, and each part should have length of 2 characters 我的目标是将每个字符串分成4个部分,每个部分的长度应为2个字符

Here is my code: 这是我的代码:

    foreach($klist as $k){
        echo $kad ."<br />";
        $part1 = trim(substr($k,0,2));
        echo $part1 ."<br />";
        $part2 = trim(substr($k,2,2));
        echo $part2 ."<br />";
        $part3 = trim(substr($k,4,2));
        echo $part3 ."<br />";
        $part4 = trim(substr($k,6,2));
        echo $part4 ."<br />";
    }

Here is the output that I get: 这是我得到的输出:

47780000
47
78
00
00
// above output is correct and as I want it to be

// however, the results bellow are wrong, there is one character missing

79110000
7
91
10
00

96040000
9
60
40
00

49321200
4
93
21
20

Can anyone help me with this code and explain to me why I have one character less in each result after the first result? 谁能帮我解决这段代码,并向我解释为什么我在第一个结果之后的每个结果中都少一个字符?

You can use the chunk_split() for Splits a string into a series of smaller parts 您可以使用chunk_split()将字符串拆分为一系列较小的部分

Example:
      echo chunk_split('96040000', 2, "<br>");

Solution for your problem: 解决问题的方法:

   $klist = [47780000, 79110000, 96040000, 49321200];
   foreach($klist as $k){
        echo chunk_split($k, 2, "<br>")."<br>";
   }

Output: 输出:

47
78
00
00

79
11
00
00

96
04
00
00

49
32
12
00

The symbol that you don't see, but it is used is a linebreak . 您没有看到但使用的符号是换行符 Remove it. 去掉它。

I don't know how you create $klist , but with file - use FILE_IGNORE_NEW_LINES as a second argument. 我不知道如何创建$klist ,但是对于file -使用FILE_IGNORE_NEW_LINES作为第二个参数。 Or apply trim to every string before processing. 或在处理之前对每根弦进行trim

<?php
$klist = [47780000,
79110000,
96040000,
49321200];
$kad = PHP_EOL;

 foreach($klist as $k){
        echo $kad ."<br />";
        $part1 = trim(substr($k,0,2));
        echo $part1 ."<br />";
        $part2 = trim(substr($k,2,2));
        echo $part2 ."<br />";
        $part3 = trim(substr($k,4,2));
        echo $part3 ."<br />";
        $part4 = trim(substr($k,6,2));
        echo $part4 ."<br />";
    }
?>

Output: 输出:

<br />47<br />78<br />00<br />00<br />
<br />79<br />11<br />00<br />00<br />
<br />96<br />04<br />00<br />00<br />
<br />49<br />32<br />12<br />00<br />

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

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