我的数据库中有这样的字符串:
$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"
)等。
我需要"Codex Azcatitlan“
我事先不知道在left和right元素之间有多少多个空格。但是,我们可以假设它总是大于1个空格。
发布于 2018-11-08 21:52:09
使用explode()的第三个参数和array_map()的组合限制部件的数量,以删除不需要的空格:
// 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));发布于 2018-11-08 21:51:17
使用preg_split并检查是否有至少2个空格字符。
$string1 = "1219.56.C38-.C382 Codex Azcatitlan";
$string2 = "1219.56.C45-.C452 Codex Cempoallan";
print_r(preg_split('/\h{2,}/', $string1));
print_r(preg_split('/\h{2,}/', $string2));如果$strings也应该在换行处拆分,则将\h更改为\s。\h是水平空格(制表符或空格),\s是任何空格。
{}在正则表达式中创建一个范围。里面的单个值是允许的字符数,里面的,表示最小和最大范围。2是最小值,没有第二个值表示任何数量的额外匹配。这与+相同,但必须有两个匹配,而不是一个匹配。
发布于 2018-11-08 22:06:22
您可以组合使用explode()和substr()
$string1 = "1219.56.C38-.C382 Codex Azcatitlan";
// explode() on spaces
$explode = explode( ' ', trim( $string1 ) ); // apply trim() just in case there are ever leading spaces
$result = array(
$explode[ 0 ], // give me everything before the first space char
trim( substr( $string1, strlen( $explode[ 0 ] ) ) ) // give me everything starting from the first space char and apply trim()
);
var_dump( $result );输出:
array(2) {
[0]=>
string(17) "1219.56.C38-.C382"
[1]=>
string(16) "Codex Azcatitlan"
}https://stackoverflow.com/questions/53209037
复制相似问题