一种使多个 preg_replace 更清晰的方法

A way to make multiple preg_replace clearer

我正在尝试将输入的字符串转换为匹配范围,这是我到目前为止所做的几行:

$targets = "1-  6;20; 20-4,71100  12";
$ranges = preg_split("/[,;]/",    // Splits sthe string into an array on any comma , or semicolon ; encountered
    preg_replace("/[\s]/", "",   // Removes remaining white spaces
        preg_replace("/[^;][\s]+/", ";",  // Replaces all white spaces that are not preceded by a semicolon ; by a semicolon ;
            preg_replace("/[\s]*[-][\s]*/", "-", $targets)   // Replaces all dashes - surrounded by any number of white spaces by a single dash -
        )
    )
);

这些线条效果很好,但我想让它更漂亮... 这是输出:

  array (size=5)
  0 => string '1-6' (length=3)
  1 => string '20' (length=2)
  2 => string '20-4' (length=4)
  3 => string '7110' (length=4)
  4 => string '12' (length=2)

问题是:有没有办法让它更清楚? (例如用数组中的替换绑定结果?) 你能给我一些例子吗,我对这些台词不是很自豪:/ 谢谢

您可以匹配内部有空格的范围,并在得到包含它们的数组后,删除所有类型的空格。

要提取范围,正则表达式可能类似于

'~\d+(?:\s*-\s*\d+)?~'

参见regex demo\d+(?:\s*-\s*\d+)? 将匹配 1+ 个数字,后跟可选的 - 序列,用 0+ 个空格括起来,然后是 1+ 个数字。

在PHP中:

$targets = "1-  6;20; 20-4,71100  12";
if (preg_match_all('~\d+(?:\s*-\s*\d+)?~', $targets, $m)) {
    print_r(preg_replace('~\s+~', '', $m[0]));
};

preg_replace('~\s+~', '', $m[0]) 将从匹配项中删除所有空格。

如果您可能有 Unicode 空格,请将 u 修饰符添加到 preg_replace 调用:

preg_replace('~\s+~u', '', $m[0]) 

输出:

Array
(
    [0] => 1-6
    [1] => 20
    [2] => 20-4
    [3] => 71100
    [4] => 12
)