这是我想要拆分成数组的字符串:
35g walnut halves A handful of thyme leaves 200g portobello mushrooms 200g white mushrooms 200g chifferini pasta 100g Petit Brebis sheep's cheese 40g honey
我想使用 preg_split
从字符串中提取各个成分。单个成分开头为:
- 由数字加字符
g
定义的数量 - 字符序列,例如
AAP
到目前为止,我有这个正则表达式模式([0-9]+g|Ahandle)
,它可以正确找到字符串中的中断,但不包括整个成分描述。我需要捕获组包含其余字符,直到下一场比赛。
为了获得数组返回,我使用这个 PHP:
preg_split("/([0-9]+g|一把)/", $ingredients_str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)
所需的输出是:
[
0 => 35g walnut halves
1 => A handful of thyme leaves
2 => 200g portobello mushrooms
etc..
]
最佳答案
您可以使用preg_match_all
提取所有描述:
preg_match_all('~(?:\d+g|A handful).*?(?=\s*(?:\d+g|A handful|$))~s', $str, $matches)
请参阅regex demo .
详细信息
(?:\d+g|A一把)
- 1+位数字后跟g
或A一把
.*?
- 任何零个或多个字符,尽可能少(?=\s*(?:\d+g|Adorf|$))
- 直到字符串中紧跟 0+ 空格且后跟 1+ 的位置数字和g
,或少数
或字符串结尾。
请参阅PHP demo :
$re = '/(?:[0-9]+g|A handful).*?(?=\s*(?:[0-9]+g|A handful|$))/s';
$str = '35g walnut halves A handful of thyme leaves 200g portobello mushrooms 200g white mushrooms 200g chifferini pasta 100g Petit Brebis sheep\'s cheese 40g honey';
if (preg_match_all($re, $str, $matches)) {
print_r($matches[0]);
}
输出:
Array
(
[0] => 35g walnut halves
[1] => A handful of thyme leaves
[2] => 200g portobello mushrooms
[3] => 200g white mushrooms
[4] => 200g chifferini pasta
[5] => 100g Petit Brebis sheep's cheese
[6] => 40g honey
)
preg_split
解决方案可能看起来像
$re = '/(?!^)\b(?=[0-9]+g|A handful)/';
$str = '35g walnut halves A handful of thyme leaves 200g portobello mushrooms 200g white mushrooms 200g chifferini pasta 100g Petit Brebis sheep\'s cheese 40g honey';
print_r(preg_split($re, $str));
请参阅demo online 。在这里,
(?!^)
- 匹配不在字符串开头的位置\b
- 字边界(?=[0-9]+g|少量)
- 紧跟 1 个以上数字的位置,然后是g
或A少数
子字符串。
关于php - 正则表达式:如何捕获以匹配的字符集开头的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64595316/