$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"
发布于 2011-10-07 15:26:58
$str =“速溶燕麦饮料-巧克力口味165g (33gx5)”;
/(?P<title>.*) (?P<grammars>\d+g) \((?P<portion>\d+g) x (?P<times>\d+)\)/
在英语中应该是这样的:
查找一个或多个字符--将其称为“标题”(速溶燕麦饮料-巧克力口味)
--然后是--
一个空格
--然后是--
一个或多个以“g”结尾的数字--称之为“语法”(165g)
--然后是--
一个空格
--然后是--
括号'(‘
--然后是--
以g结尾的一个或多个数字(\d+) --调用\d+g‘\d+’(33g)
--然后是--
后跟x和空格的空格。(X)
--然后是--
一个或多个数字--称之为“时间”( 5)
发布于 2011-10-07 14:47:14
出自preg_match()手册
命名子模式现在接受语法(?)和(?'name')以及(?P)。以前的版本仅接受(?P)。
所以,(?P<grammars>.*)会让你在$m['grammars']中有一个值
\d+匹配1个或多个数字,g匹配字母g
匹配任何字符的贪婪匹配,0次或更多次-在您的示例中,此匹配将放入title或grammars .*变量中。
我建议您阅读一些基本的正则表达式教程-- .*构造是非常基础的
发布于 2011-10-07 14:48:00
意思是这样的:
# (?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的输出。应该使用正则表达式帮助器。帮助很大:)
https://stackoverflow.com/questions/7683848
复制相似问题