Php 正则表达式删除带数字的单词
我想在我的产品名称中删除带有数字(参考)或小字(2个字符或更少)的单词,但我找不到好的正则表达式 一些例子:Php 正则表达式删除带数字的单词,php,regex,Php,Regex,我想在我的产品名称中删除带有数字(参考)或小字(2个字符或更少)的单词,但我找不到好的正则表达式 一些例子: “链式防重启ECS-2035”应变为“链式防重启” “Guide 35 cm Oregon Intenz”应改为“Guide Oregon Intenz” “Tronçonneuse sans fil-AKE 30 li-Guide 30 cm 36 V”应变为“Tronçonneuse sans fil-AKE-Guide” 我正在用PHP做这件事: preg_replace('#
- “链式防重启ECS-2035”应变为“链式防重启”
- “Guide 35 cm Oregon Intenz”应改为“Guide Oregon Intenz”
- “Tronçonneuse sans fil-AKE 30 li-Guide 30 cm 36 V”应变为“Tronçonneuse sans fil-AKE-Guide”
preg_replace('#([^A-Za-z-]+)#', ' ',' '.wd_remove_accents($modele).' ');
在回调函数中使用preg_replace_callback和filter 这将适用于所有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);
对于示例中的组合,下面的正则表达式可以:
/\b(?:[-A-Za-z]+[0-9]+|[0-9]+[-A-Za-z]+|\d{1,2}|[A-Za-z]{1,2})\b/
然后用空字符串替换匹配项
但是,它不允许像aaa897bb
这样的字符串,只允许aaa786
或876aaa
(和可选破折号)。
我不知道您需要什么-您必须在细化正则表达式之前更详细地指定规则。您不需要在正则表达式中执行您知道的所有操作:
<?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;
要处理类似于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);
“删除带数字的单词(参考)或小词(lte 2字符)”这就是为什么你不能这样做,除非你应该为函数提供在带数字的字符串中查找的精确匹配项。e、 g.您应提供cm、li、V、ecs等。那么此字符串中的ecs
如何Chaine-anti-rebond ecs-2035
应成为Chaine-anti-rebond
????????