这个正则表达式是什么意思(php)

时间:2011-10-07 06:41:37

标签: php regex

$str = "Instant Oats Drink - Chocolate Flavour 165g (33g x 5)";

preg_match('/(?P<title>.*) (?P<grammars>\d+g) \((?P<portion>\d+g) x (?P<times>\d+)\)/', $str, $m);

echo "Title : " . $m['title'] . '<br />';
echo "Grammars : " . $m['grammars'] . '<br />';
echo "Portion : " . $m['portion'] . '<br />';
echo "Times : " . $m['times'] . '<br />';

我真的不知道preg_match有什么意义。例如"?P<title>""\d+g"

3 个答案:

答案 0 :(得分:2)

来自preg_match()的手册:

命名子模式现在接受语法(?)和(?'name')以及(?P)。以前的版本只接受(?P)。

因此,(?P<grammars>.*)会让您在$m['grammars']

中获得一个值

\d+匹配1个或多个数字,g匹配字母g

任何字符的

.*贪婪匹配,0次或更多次 - 在您的情况下,此匹配将被放入titlegrammars匹配变量中。

我建议您阅读一些基本的正则表达式教程 - .*构造是一个非常基本的构造

答案 1 :(得分:2)

意思是:

# (?P<title>.*) (?P<grammars>\d+g) \((?P<portion>\d+g) x (?P<times>\d+)\)

# 
# Match the regular expression below and capture its match into
#  backreference with name “title” «(?P<title>.*)»

#    Match any single character that is not a line break character «.*»
#       Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
# Match the character “ ” literally « »
# Match the regular expression below and capture its match into backreference with name “grammars” «(?P<grammars>\d+g)»
#    Match a single digit 0..9 «\d+»
#       Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
#    Match the character “g” literally «g»
# Match the character “ ” literally « »
# Match the character “(” literally «\(»
# Match the regular expression below and capture its match into backreference with name “portion” «(?P<portion>\d+g)»
#    Match a single digit 0..9 «\d+»
#       Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»

#    Match the character “g” literally «g»
# Match the characters “ x ” literally « x »
# Match the regular expression below and capture its match into backreference with name “times” «(?P<times>\d+)»
#    Match a single digit 0..9 «\d+»
#       Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
# Match the character “)” literally «\)»

这是regexbuddy的输出。你应该使用正则表达式助手。帮助很多:)

答案 2 :(得分:1)

$ str =“速溶燕麦饮料 - 巧克力味165g(33g x 5)”;

/(?P<title>.*) (?P<grammars>\d+g) \((?P<portion>\d+g) x (?P<times>\d+)\)/

在英语中它会是这样的:

寻找一个或多个角色 - 称之为'标题'(即食燕麦饮料 - 巧克力味)

- 接着是 -

空格

- 接着是 -

一个或多个以'g'结尾的数字 - 称之为'grammars'(165g)

- 接着是 -

空格

- 接着是 -

括号'('

- 接着是 -

以g结尾的一个或多个数字(\ d +) - 调用\ d + g'部分'(33g)

- 接着是 -

后跟x后跟空格的空格。 (x)

- 接着是 -

一个或多个数字 - 称之为'次'(5)