preg_replace 用于获取食谱字符串的重量和搜索词的正则表达式

preg_replace regex for getting weight and search term for recipe string

我有一组食谱中项目的数据,它们都遵循相似的格式。

2 ripe avocados, halved, stoned, peeled, coarsely chopped
125g tin chickpeas, rinsed, drained  
250g cherry tomatoes, chopped  
2 fresh red birdseye chillies, seeded, finely chopped  
1/2 cup coriander leaves
1 tablespoon lime juice  
2 tablespoons plain flour  
2 teaspoons sumac  
8 (about 800g) white fish fillets (such as bream or whiting)
1 tablespoon vegetable oil

我要执行的操作会忽略第一个逗号 (,) 之后的所有内容,因为它与我要查找的内容无关。那么数据集将如下所示:

2 ripe avocados
125g tin chickpeas  
250g cherry tomatoes
2 fresh red birdseye chillies
1/2 cup coriander leaves
1 tablespoon lime juice  
2 tablespoons plain flour  
2 teaspoons sumac  
8 (about 800g) white fish fillets (such as bream or whiting)
1 tablespoon vegetable oil

现在删除括号内的所有内容,生成以下数据集:

2 ripe avocados
125g tin chickpeas  
250g cherry tomatoes
2 fresh red birdseye chillies
1/2 cup coriander leaves
1 tablespoon lime juice  
2 tablespoons plain flour  
2 teaspoons sumac  
8 white fish fillets
1 tablespoon vegetable oil

最后,我想删除一些集合词,它们不是很多,我有一个列表,但在这个例子中,它将是 'tin','fresh' 和 'ripe'。导致我正在寻找的两件事,即搜索词和音量。如下:

2 avocados
125g chickpeas  
250g cherry tomatoes
2 red birdseye chillies
1/2 cup coriander leaves
1 tablespoon lime juice  
2 tablespoons plain flour  
2 teaspoons sumac  
8 white fish fillets
1 tablespoon vegetable oil

当然这可以通过正则表达式实现,目前我正在使用爆炸和其他迭代等来尝试实现这一点,因为正则表达式不是我的强项,但它不是正确的方法。

如有任何帮助或建议,我们将不胜感激!归根结底,这样做的原因是因为我有一个食品和数量的数据库,我试图与之进行比较。

example here

替换

,.*$|\([^)]+\)|\b(tin|fresh|ripe)\b

with ''(然后您可能需要将'{2,}'替换为''来处理例如 125g tin chickpeas going to 125g chickpeas (double space).

,.*$ 匹配从逗号到行尾的所有内容,\([^)]+\) 替换括号中的匹配项(无嵌套括号),tin|fresh|ripe 匹配单词 'tin'、'fresh' 和 'ripe'。 \b 匹配 'word boundary',例如'stripe' 中的 'ripe' 不会被删除。

在 PHP 中,您可以使用类似 preg_replace 的内容,例如

$recipe = preg_replace('/,.*$|\([^)]+\)|\b(tin|fresh|ripe)\b/', '', $recipe)
// fix multiple-spaces
$recipe = preg_replace('/ {2,}/', ' ', $recipe)