将大字符串分成多个小字符串 - PHP

Divide big string in multiple small one - PHP

我从数据库中获取了一些长字符串,我需要对其进行解析,使其不是一个大字符串而是多个字符串,每个字符串都有 2 个字符。

让我们举个例子: 我连接到 table,得到这个字符串:B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5,之后我必须成对解析这个字符串,所以:

B1 C1 F4 G6 H4 I7 J1 J8 L5 O6 P2 Q1 R6 T5 U8 V1 Z5

然后做一些循环来插入一些东西。 (例如在这个 2 字符字符串的末尾添加随机数并在之后回显)

我在想类似的事情:

$string ="B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5";
$string1 = substr($string,0,2);
$string2 = substr($string,2,3);

但我相信有一些更简单的方法可以做到这一点,而且当我不知道字符串有多长时,我的方法也有问题。

感谢您的任何建议。

$string = "B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5";
$newstring = implode(str_split($string, 2), ' ');
echo $newstring;

您可以为此使用 preg_replace_callback()

echo preg_replace_callback('/../', function($match) {
    return $match[0] . rand(0, 9);
}, $s);

它每两个字符运行一次该函数,您可以附加一个您选择的字符。

preg_match_all 是我的选择:

$string = 'B1C1F4G6H4I7J1J8L5O6P2Q1R6T5U8V1Z5';
// let's find all the chunks of two chars
preg_match_all("/.{1,2}/", $string, $matches);
// there you go
var_dump($matches[0]);