【问题标题】:Split a string using preg_split使用 preg_split 拆分字符串
【发布时间】:2021-01-25 15:49:06
【问题描述】:

我正在寻找一种使用正则表达式在每组数字之后拆分以下字符串的方法。我对此很陌生,我很难理解如何使用正确的正则表达式格式。

$string = '521158525 Interest Being Subordinated: 521855248 Benefiting Interest: 511589923';

preg_split("/([0-9])/", $string, 0, PREG_SPLIT_NO_EMPTY);

【问题讨论】:

  • 请发布您想要的结果

标签: php split preg-split


【解决方案1】:

要在每组数字之后进行拆分,您可以使用模式来仅匹配单词边界之间的数字。

然后使用\K 忘记匹配的内容,直到到目前为止匹配可选的水平空白字符以在拆分后不获取尾随空白。

$string = '521158525 Interest Being Subordinated: 521855248 Benefiting Interest: 511589923';
$result = preg_split(
    "\b\d+\b\h*\K",
    $string,
    0,
    PREG_SPLIT_NO_EMPTY
);

print_r($result);

输出

Array
(
    [0] => 521158525
    [1] => Interest Being Subordinated: 521855248
    [2] => Benefiting Interest: 511589923
)

【讨论】:

  • 完美!感谢您的帮助
  • @JohnColeman 如果对解决问题有帮助,请随意mark the answer,点击答案左侧的✓。请注意,您会得到 2 reputation points 接受解决方案。
【解决方案2】:

您可能需要在函数调用中再添加一个标志PREG_SPLIT_DELIM_CAPTURE:

<?php
$string = '521158525 Interest Being Subordinated: 521855248 Benefiting Interest: 511589923';

$res = preg_split("/:?\s*([0-9]+)\s?/", $string, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

var_export($res);

结果:

array (
  0 => '521158525',
  1 => 'Interest Being Subordinated',
  2 => '521855248',
  3 => 'Benefiting Interest',
  4 => '511589923',
)

Share PHP code

【讨论】:

  • 如何保留文本并在数字后拆分?例如:从属权益:521855248 受益权益:511589923
猜你喜欢
  • 2013-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
相关资源
最近更新 更多