php - 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 个空格。
解决方案
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));
推荐阅读
- php - 在php中将数组字符串转换为csv
- angular - Angular:如何访问 JSON 的父项和子项以显示面包屑
- css - 如何使用css将svg放在一个有背景的圆圈内?
- mysql - 更新和子查询的问题。一对多
- c# - “字典中不存在给定的键”EmailAddresses[EmailAddressKey.EmailAddress1].Address
- javascript - 谷歌:生成登录提示的权限被拒绝
- python - Python:跳过所有没有字母/数字的行
- android - 已经存在:com.google.android.material.internal.package-info
- typescript - Chrome 开发工具 - 使用 TypeScript 时变量悬停不符合预期
- microsoft-teams - 如何在连接器设置中集成外部帐户