正则表达式 - preg_match_all 减少数组结果
Reg Exp - preg_match_all reduce array result
这是我的注册表达式“[c]?[\d+|\D+]\s*”。我的输入是 "c7=c4/c5*100",结果是:
Array
(
[0] => Array
(
[0] => c7
[1] => =
[2] => c5
[3] => +
[4] => c3
[5] => *
[6] => 1
[7] => 0
[8] => 0
)
)
但我想要的是:
Array
(
[0] => Array
(
[0] => c7
[1] => =
[2] => c5
[3] => +
[4] => c3
[5] => *
[6] => 100
)
)
我似乎无法完成最后一部分工作,我不知道下一步该怎么做 - 有人能帮忙吗?
谢谢,
保罗
您指定了一个 character class [\d+|\D+]
which would match any of the specified characters. I think you meant using an or |
with a grouping 构造 c?(?:\d+|\D+)\s*
但在那种情况下它将匹配 c 后跟 \d+
或 \D
以便匹配 =
在它之后签名,导致 c=
作为匹配项,/c
作为匹配项。
尝试匹配可选的 c c?
后跟一位或多位数字或 |
不匹配数字 \D
$re = '/c?\d+|\D/m';
$str = 'c7=c4/c5*100';
preg_match_all($re, $str, $matches);
print_r($matches);
这将导致:
Array
(
[0] => Array
(
[0] => c7
[1] => =
[2] => c4
[3] => /
[4] => c5
[5] => *
[6] => 100
)
)
这是我的注册表达式“[c]?[\d+|\D+]\s*”。我的输入是 "c7=c4/c5*100",结果是:
Array ( [0] => Array ( [0] => c7 [1] => = [2] => c5 [3] => + [4] => c3 [5] => * [6] => 1 [7] => 0 [8] => 0 ) )
但我想要的是:
Array ( [0] => Array ( [0] => c7 [1] => = [2] => c5 [3] => + [4] => c3 [5] => * [6] => 100 ) )
我似乎无法完成最后一部分工作,我不知道下一步该怎么做 - 有人能帮忙吗?
谢谢, 保罗
您指定了一个 character class [\d+|\D+]
which would match any of the specified characters. I think you meant using an or |
with a grouping 构造 c?(?:\d+|\D+)\s*
但在那种情况下它将匹配 c 后跟 \d+
或 \D
以便匹配 =
在它之后签名,导致 c=
作为匹配项,/c
作为匹配项。
尝试匹配可选的 c c?
后跟一位或多位数字或 |
不匹配数字 \D
$re = '/c?\d+|\D/m';
$str = 'c7=c4/c5*100';
preg_match_all($re, $str, $matches);
print_r($matches);
这将导致:
Array
(
[0] => Array
(
[0] => c7
[1] => =
[2] => c4
[3] => /
[4] => c5
[5] => *
[6] => 100
)
)