【问题标题】:php preg_split or explode. Not removing the characterphp preg_split 或爆炸。不删除字符
【发布时间】: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


【解决方案1】:

我猜每个子字符串都必须以大写字母开头。然后这样做:

$string = "Henry the horse, Billy the donkey, Harry the mule, George, the hippo";

preg_match_all("~[A-Z].*?(?:$|,)(?!\s*[a-z])~", $string, $result);

$result[0] 将包含以下输出:

[
    "Henry the horse,"
    "Billy the donkey,"
    "Harry the mule,"
    "George, the hippo"
]

【讨论】:

  • 是的,字符串来自一个数组,其中每个成员都以大写字母开头,所以这应该可以解决问题。我不知道 preg_match_all 返回了一个数组!我将不得不了解正则表达式(教程时间)。谢谢。
【解决方案2】:

您可以使用环视或(*SKIP)(*FAIL)。要么使用,(?! the),要么使用, the(*SKIP)(*FAIL)|,preg_split()

点击我的手机

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 2011-12-10
    • 2012-04-06
    • 1970-01-01
    相关资源
    最近更新 更多