preg_match_all用特殊的caracteres分割条件表达式

时间:2017-10-12 02:28:29

标签: php regex preg-match-all

我有这种格式的数据:

Randomtext1(#random2#, #random4#) == 1 && Randomtext2 (ran dom) != 2 || #Randomtext3# > 3 && Randomtext4 (random5,random7,random8) || Randomtext5  (Randomtext4 (random5,random7,random8), random10) < Randomtext11()

用这个:

preg_match_all("~\w+(?:\s*(\([^()]*+(?:(?1)[^()]*)*+\)))?~", $expression, $matches);

我获得:

0 => 'Randomtext1(#random2#, #random4#)',
1 => '1',
2 => 'Randomtext2 (ran dom)',
3 => '2',
4 => 'Randomtext3',
5 => '3',
6 => 'Randomtext4 (random5,random7,random8)',
7 => 'Randomtext5  (Randomtext4 (random5,random7,random8), random10)',
8 => 'Randomtext11()',

但我想:

0 => 'Randomtext1(#random2#, #random4#)'
1 => '1'
2 => 'Randomtext2 (ran dom)'
3 => '2'
4 => '#Randomtext3#'
5 => '3',
6 => 'Randomtext4 (random5,random7,random8)',
7 => 'Randomtext5  (Randomtext4 (random5,random7,random8), random10)',
8 => 'Randomtext11()',

我的问题,我在第4元丢失了#

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

Recieved\w *您还需要允许0-9a-zA-Z_,您可以使用更改或字符类。

#

[#\w]+

完整示例:

(?:#|\w)+

演示:https://3v4l.org/75eGQ

正则表达式演示:https://regex101.com/r/1PYvpO/1/

  

\ w代表“单词字符”。它始终与ASCII字符[A-Za-z0-9_]匹配。请注意包含下划线和数字。在大多数支持Unicode的版本中,\ w包含来自其他脚本的许多字符。关于实际包含哪些字符存在很多不一致。通常包括来自字母脚本和表意文字的字母和数字。除了下划线之外的连接符标点和非数字的数字符号可能包括也可能不包括。 XML Schema和XPath甚至包括\ w中的所有符号。

* https://www.regular-expressions.info/shorthand.html

答案 1 :(得分:0)

我想我会在preg_split()使用这个更简单的模式。这对眼睛来说要容易得多。

代码:(PHP Demo)(Pattern Demo

$string='Randomtext1(#random2#, #random4#) == 1 && Randomtext2 (ran dom) != 2 || #Randomtext3# > 3 && Randomtext4 (random5,random7,random8) || Randomtext5  (Randomtext4 (random5,random7,random8), random10) < Randomtext11()';
var_export(preg_split('/ [=!&|<>]{1,2} /',$string));

输出:

array (
  0 => 'Randomtext1(#random2#, #random4#)',
  1 => '1',
  2 => 'Randomtext2 (ran dom)',
  3 => '2',
  4 => '#Randomtext3#',
  5 => '3',
  6 => 'Randomtext4 (random5,random7,random8)',
  7 => 'Randomtext5  (Randomtext4 (random5,random7,random8), random10)',
  8 => 'Randomtext11()',
)

这将匹配并拆分==&&!=>||<上的字符串(有一个)分界值周围的前导和一个尾随空格 - 在格式化文本中很难看到)

相关问题