【发布时间】:2011-12-27 06:42:25
【问题描述】:
在 php 中搜索字符串并找到不区分大小写的匹配项的最佳方法是什么?
例如:
$SearchString = "This is a test";
从这个字符串中,我想找到单词 test、TEST 或 Test。
谢谢!
编辑
我还应该提到我想搜索字符串,如果它包含我的黑名单数组中的任何单词,请停止处理它。因此,“测试”的精确匹配很重要,但是大小写并不重要
【问题讨论】:
标签: php
在 php 中搜索字符串并找到不区分大小写的匹配项的最佳方法是什么?
例如:
$SearchString = "This is a test";
从这个字符串中,我想找到单词 test、TEST 或 Test。
谢谢!
编辑
我还应该提到我想搜索字符串,如果它包含我的黑名单数组中的任何单词,请停止处理它。因此,“测试”的精确匹配很重要,但是大小写并不重要
【问题讨论】:
标签: php
如果你想查找单词,并且想要禁止“FU”而不是“fun”,你可以使用正则表达式whit \b,其中\b 标记单词的开始和结束, 所以如果你搜索 "\bfu\b" 如果不匹配 "fun", 如果你在分隔符后面添加一个“i”,它的搜索大小写不敏感, 如果你有一个像“fu”“foo”“bar”这样的单词列表,你的模式可能看起来像: "#\b(fu|foo|bar)\b#i",也可以使用变量:
if(preg_match("#\b{$needle}\b#i", $haystack))
{
return FALSE;
}
编辑,添加多字示例,在 cmets 中要求字符转义:
/* load the list somewhere */
$stopWords = array( "word1", "word2" );
/* escape special characters */
foreach($stopWords as $row_nr => $current_word)
{
$stopWords[$row_nr] = addcslashes($current_word, '[\^$.|?*+()');
}
/* create a pattern of all words (using @ insted of # as # can be used in urls) */
$pattern = "@\b(" . implode('|', $stopWords) . ")\b@";
/* execute the search */
if(!preg_match($pattern, $images))
{
/* no stop words */
}
【讨论】:
你可以做一些事情之一,但我倾向于使用其中之一:
您可以使用stripos()
if (stripos($searchString,'test') !== FALSE) {
echo 'I found it!';
}
您可以将字符串转换为一种特定的大小写,并使用strpos() 进行搜索
if (strpos(strtolower($searchString),'test') !== FALSE) {
echo 'I found it!';
}
我两者都做,没有偏好 - 一个可能比另一个更有效(我怀疑第一个更好)但我实际上不知道。
举几个更可怕的例子,你可以:
i 修饰符的正则表达式if (count(explode('test',strtolower($searchString))) > 1)
【讨论】:
stripos,我想。大概它在找到匹配项时停止搜索,我猜它在内部会转换为小写(或大写),所以这和你得到的一样好。
【讨论】:
http://us3.php.net/manual/en/function.preg-match.php
取决于你是否只想匹配
在这种情况下,你会这样做:
$SearchString= "This is a test";
$pattern = '/[Test|TEST]/';
preg_match($pattern, $SearchString);
【讨论】:
我没有正确阅读问题。如其他答案所述,stripos 或 preg_match 函数将完全符合您的要求。
我最初提供了 stristr 函数作为答案,但如果你只是想在另一个字符串中查找一个字符串,你实际上不应该使用它,因为它返回除了搜索参数之外的字符串的其余部分。
【讨论】: