Php 如何制作正确的正则表达式
我想得到${1}=Title,${2}=Open,${3}=Bla-Bla-Bla 从Php 如何制作正确的正则表达式,php,regex,Php,Regex,我想得到${1}=Title,${2}=Open,${3}=Bla-Bla-Bla 从 这是一个玩耍和学习正则表达式的好地方。像这样的东西怎么样: $str = <<<STR {{Title|Open Bla-bla-bla }} STR; $matches = array(); if (preg_match("/^\{\{([^\|]+)\|([^\n]+)(.*)\}\}$/s", $str, $matches)) { var_dump($matches);
这是一个玩耍和学习正则表达式的好地方。像这样的东西怎么样:
$str = <<<STR
{{Title|Open
Bla-bla-bla
}}
STR;
$matches = array();
if (preg_match("/^\{\{([^\|]+)\|([^\n]+)(.*)\}\}$/s", $str, $matches)) {
var_dump($matches);
}
这意味着,在$matches[1]
、$matches[2]
和$matches[3]
上使用后,您将得到所需的:-)
解释正则表达式:
- 从字符串开头匹配:
^
- 两个必须转义的
字符,因为它们具有特殊含义{
- 任何不是|的东西,至少一次:
[^\|]+
- 在
之间捕获它——作为结果的第一部分返回()
也必须转义|
- 在
- 必须转义的
字符|
- 任何不是换行符的内容,至少一次:
[^\n]+
- 在
之间,所以它也被捕获——结果的第二部分()
- 在
几乎可以多次“任何东西”*
- 在
之间,所以它也被捕获——结果的第三部分()
- 在
- 最后,还有两个
(也转义)}
- 和字符串结尾:
$
s
(dotall)修饰符;请参见,关于这一点。在Perl中:
/\{\{ # literal opening braces
(.*?) # some characters except new line (lazy, i. e. as less as possible)
\| # literal pipe
(.*?) # same as 2 lines above
\n # new line
([\s\S]*?) # any character, including new line (lazy)
\}\}/x; # literal closing braces
生成更精确的解决方案取决于要提取字段的确切规则
$str = <<<STR
{{Title|Open
Bla-bla-bla
}}
STR;
$matches = array();
if (preg_match("/^\{\{([^\|]+)\|([^\n]+)(.*)\}\}$/s", $str, $matches)) {
var_dump($matches);
}
array
0 => string '{{Title|Open
Bla-bla-bla
}}' (length=28)
1 => string 'Title' (length=5)
2 => string 'Open' (length=4)
3 => string '
Bla-bla-bla
' (length=14)
/\{\{ # literal opening braces
(.*?) # some characters except new line (lazy, i. e. as less as possible)
\| # literal pipe
(.*?) # same as 2 lines above
\n # new line
([\s\S]*?) # any character, including new line (lazy)
\}\}/x; # literal closing braces