在每个 wole 数字后分割一个字符串

问题描述 投票:0回答:3

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

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

preg_split("/([0-9])/", $string, 0, PREG_SPLIT_NO_EMPTY);
php split preg-split
3个回答
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
)

0
投票

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

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',
)

分享PHP代码


0
投票

匹配一个或多个数字,忘记您匹配了它们(

\K
),然后在下一个空格上爆炸。 演示

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

var_export(
    preg_split('/\d+\K /', $str)
);

干净的输出,没有尾随空格:

array (
  0 => '521158525',
  1 => 'Interest Being Subordinated: 521855248',
  2 => 'Benefiting Interest: 511589923',
)
© www.soinside.com 2019 - 2024. All rights reserved.