php - 正则表达式:如何捕获以匹配的字符集开头的组

标签 php regex

这是我想要拆分成数组的字符串:

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..
]

参见regex 101

最佳答案

您可以使用preg_match_all提取所有描述:

preg_match_all('~(?:\d+g|A handful).*?(?=\s*(?:\d+g|A handful|$))~s', $str, $matches)

请参阅regex demo .

详细信息

  • (?:\d+g|A一把) - 1+位数字后跟gA一把
  • .*? - 任何零个或多个字符,尽可能少
  • (?=\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 个以上数字的位置,然后是 gA少数子字符串。

关于php - 正则表达式:如何捕获以匹配的字符集开头的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64595316/

相关文章:

php - 为什么我在查询中得到资源 ID 13?

php - mod_rewrite .htaccess 文件

javascript - 将字符串(Revit 公式)转换为 JavaScript 对象

javascript - 获取文本信息,对它们进行排序和编号,并在编号和每个 block 之后放置 ";"

R:如何让 grep 返回匹配项,而不是整个字符串

javascript - javascript中的多个if else条件

php - 在 Magento 中,如何读取 exception.log?

php - Laravel 5.2 PDO 终端​​异常

javascript - 带分隔符的三个可选部分的正则表达式

javascript - 如何编写一个正则表达式来匹配除左括号和右括号以及它们之间的任何内容之外的所有内容