我想在我的产品名称中删除带有数字(参考)或小单词(2 个字符或更少)的单词,但我找不到好的正则表达式。
一些例子:
- "
- Chaine反重粘合ECS-2035"应成为"Chaine反重粘合" "
- 指南35厘米俄勒冈Intenz"应成为"指南俄勒冈Intenz" "Tronçonneuse sans fil AKE 30 LI - Guide
- 30 cm 36 V"应变为"Tronçonneuse sans fil AKE - Guide"
我在 PHP 中这样做:
preg_replace('#([^A-Za-z-]+)#', ' ',' '.wd_remove_accents($modele).' ');
您不需要在RegExp中执行所有操作,您知道:
<?php
$str = "Chaine anti-rebond ECS-2035 cm 30 v";
$result = array();
$split = explode(" ", $str); //Split to an array
foreach ($split as $word) {
if ((strlen($word) <= 2) || (preg_match("|'d|", $word))) { //If word is <= 2 char long, or contains a digit
continue; //Continue to next iteration immediately
}
$result[] = $word; //Add word to result array (would only happen if the above condition was false)
}
$result = implode(" ", $result); //Implode result back to string
echo $result;
对于基于单词的字符串操作,解析字符串本身,在单词的基础上精确地调节您想要的内容,通常比字符串级 RegEx 要好得多。
要像tronçonneuse
那样处理 unicode 字符,您可以使用:
/'b(?:['pL-]+'pN+|'pN+['pL-]+|'pN+|'pL{1,2})'b/
其中'pL
代表任何字母,'pN
代表任何数字。
您的要求对于最终答案来说不够具体,但这可以为您的示例执行此操作:
$subject = 'Tronçonneuse sans fil AKE 30 LI - Guide 30 cm 36 V';
$regex = '/(''s+''w{1,2}(?=''W+))|(''s+[a-zA-Z0-9_-]+''d+)/';
$result = preg_replace($regex, '', $subject);
好吧,对于示例中的组合,以下正则表达式就可以了:
/'b(?:[-A-Za-z]+[0-9]+|[0-9]+[-A-Za-z]+|'d{1,2}|[A-Za-z]{1,2})'b/
然后只需将匹配项替换为空字符串即可。
但是,它不允许像aaa897bbb
这样的字符串 - 只有aaa786
或876aaa
(以及可选的破折号)。我不知道您需要什么 - 在优化正则表达式之前,您必须更详细地指定规则。
在回调函数中使用preg_replace_callback和过滤器 http://www.php.net/manual/en/function.preg-replace-callback.php
这将适用于所有 3 个测试字符串:
<?php
$str = "Tronçonneuse sans fil AKE 30 LI - Guide 30 cm 36 V";
function filter_cb($matches)
{
$word = trim($matches[0]);
if ($word !== '-' && (strlen($word) <= 2 || (preg_match("/'d/", $word)))) {
return '';
}
return $matches[0];
}
$result = preg_replace_callback('/(['p{L}'p{N}-]+'s*)/u', "filter_cb", $str);
echo trim($result);