下面是我想要分割成一个数组的字符串:
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定义的数量。A handful到目前为止,我有一个regex模式([0-9]+g|A handful),它正确地找到字符串中的断线,但不包括整个成分描述。我需要捕捉组包括其余的字符,直到下一次匹配。
为了获得数组返回,我使用了以下PHP:
preg_split("/([0-9]+g|A handful)/", $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..
]请参阅regex 101
发布于 2020-10-29 16:33:29
您可以使用preg_match_all提取所有描述:
preg_match_all('~(?:\d+g|A handful).*?(?=\s*(?:\d+g|A handful|$))~s', $str, $matches)见regex演示。
详细信息
(?:\d+g|A handful) - 1+数字后面跟着g或A handful.*? -任何零或多个字符,尽可能少(?=\s*(?:\d+g|A handful|$)) -直到字符串中的一个位置,该位置紧跟在0+空格后面,后面跟着1+位数和g,或者是A handful或字符串的末尾。$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));见在线演示。这里,
(?!^) -匹配不位于字符串开头的位置。\b -字边界(?=[0-9]+g|A handful) -一个紧跟在1+数字后面的位置,然后是g或A handful子字符串。https://stackoverflow.com/questions/64595316
复制相似问题