我有一个插入查询,它将各种单词添加到搜索表中,用于基于其他表的现有内容对我的网站进行关键字搜索。
我的问题是,虽然我有一个常见的单词文本文件,不包括像"answers"和"the"这样的单词,我也希望消除长度小于3个字符的数字和单词。
有人能帮忙吗?
$stripChars = array('.', ',', '!', '?', '(', ')', '%', '&', '"', '*', ':', ';', '@', ' - ', '/', '''');
$string = str_replace($stripChars, ' ', $string);
$string = str_replace(' ', ' ', $string);
$words = explode(' ', $string);
return array_diff($words, $this->commonwords);
你可以用它来删除少于3个字符的单词:
$replaced = preg_replace('~'b[a-z]{1,2}'b'~', '', $text);
也可以用这个来删除数字:
$replaced = preg_replace('/[0-9]+/', '', $text);
您可以使用preg_replace
函数在PHP中使用结构化Regex调用来实现您想要实现的目标。然而,看看你的问题上的代码,有很多可以通过使用正确的Regex和Preg_replace函数来改进:
$stripChars = array('.', ',', '!', '?', '(', ')', '%', '&', '"', '*', ':', ';', '@', ' - ', '/', ''''); $string = str_replace($stripChars, ' ', $string);
让我们面对现实吧,这看起来不是很清晰。假设您只是想删除非字母数字字符,这可以简化为:
$string = preg_replace("/[^a-z0-9_'s-]/i","",$string);
它告诉PHP替换所有不是的字符(由^
克拉表示):a-z (/i
表示不区分大小写),而不是0-9,不是下划线_
,不是空白字符's
或破划线-
。然后将它们替换为空(第二个字符串部分),从而有效地删除。
显然,你可以调整方括号中的内容来满足你的需要(见后面会发生的情况…)。
添加到你的下一个部分:
$string = str_replace(' ', ' ', $string);
这似乎是你想用一个空格字符替换多个空格,同样,preg_replace
可以为你做得很好,很简洁:
$string = preg_replace("/'s+/", " ",$string);
其中's
为空白字符,+
表示返回"greedy and as many as possible"
和您的原始请求,这是为了删除2个或更少字符的数字和单词,preg_replace可以使用这个答案的第1部分中的代码来简单地包括数字,通过从[^a-z0-9_'s-]
块中省略数字,因此:[^a-z_'s-]
数字现在将被删除。
要删除短单词,可以使用:
$string = preg_replace("/'b[a-z]{1,2}'b/i","",$string);
这将列出具有单词边界'b
的单词,然后定义方括号[a-z]
中长度在最小1到最大2 {1,2}
之间的字符的任何集合应该被标记,并且'i
再次使其不区分大小写,从而删除这些单词。
把它们放在一起,你就有了:
///remove anything that is not letters or underscore or whitespace
$string = preg_replace("/[^a-z_'s-]/i","",$string);
/// remove short words
$string = preg_replace("/'b[a-z]{1,2}'b/i","",$string);
/// finally remove excess whitespaces
$string = preg_replace("/'s+/", " ",$string);
空格的删除放在最后,因为删除短单词会在单词的每一边留下空格,从而导致更长的空白块。
可能有一种方法可以将Regex组合成单个(或至少更少)查询/查询,但恐怕我不太擅长组合Regex调用。但是上面的代码比你现在的代码更聪明、更简洁、更强大。同时回答你的问题。
编辑:要删除数字,可以使用以下preg_replace
代码:
$string = preg_replace("/'d+/","",$string);