首页 > 解决方案 > PHP 以多个空格爆炸

问题描述

我有来自这样的数据库的字符串:

$string1 = "1219.56.C38-.C382                 Codex Azcatitlan";
$string2 = "1219.56.C45-.C452                      Codex Cempoallan";

我如何将它们分成:

["1219.56.C38-.C382", "Codex Azcatitlan"]
["1219.56.C45-.C452", "Codex Cempoallan"]

请注意,如果我使用了 $stringar1 = explode(" ", $string1) 等。我会得到这个:

array(3)
(
    [0] => string "1219.56.C38-.C382"
    [1] => string "Codex"
    [2] => string "Azcatitlan"
)

等等

我需要“法典 Azcatitlan”

我事先不知道左右元素之间有多少个多重空格。但是,我们可以假设它总是超过 1 个空格。

标签: php

解决方案


Limit number of parts with third argument of explode() with a combination of array_map() to remove unwanted spaces:

// this means you will have 2 items and all other spaces 
// after first one  will not be used for `explod`ing
$r = array_map('trim', explode(" ", $string1, 2));

推荐阅读