【发布时间】:2019-04-27 05:16:57
【问题描述】:
我一直在尝试多种方法来解决我的问题,但发现了一种糟糕的解决方法,但我想知道是否还有其他方法。 我有一串由逗号分隔的几个子字符串。我可以使用 preg_split 或explode 将其拆分为一个数组。但是一些子字符串还包含我不想分成单独的数组成员的逗号。我的解决方法是在每个字符串的末尾添加一个句号,然后告诉explode 只在“.”上拆分。 示例字符串:
$string = "Henry the horse, Billy the donkey, Harry the mule, George, the hippo";
解决方法
$string = "Henry the horse., Billy the donkey., Harry the mule., George, the hippo.";
$list = explode('.,',$string);
我一辈子都想不出任何方法来告诉程序 George 之后的逗号不是子字符串的结尾。 另一个(相关)问题是我想在逗号处拆分字符串,但在数组成员中包含逗号。
==> Henry the horse,
==> Billy the donkey,
==> Harry the mule,
==> George, the hippo,
我的想法只是在之后再次添加它们。有没有更简单的方法? 换句话说,有没有办法在分隔符处拆分但将分隔符保留在数组成员中?
【问题讨论】:
-
如果你不知道如何判断逗号是子字符串的一部分还是分隔符的逻辑,那么就不可能告诉 PHP 去做。那么逻辑是什么?
-
对我的评论或以下答案有任何反馈吗?
标签: php regex explode preg-split