Php 搜索字符串中的单词
在php中搜索字符串并找到不区分大小写的匹配项的最佳方法是什么 例如:Php 搜索字符串中的单词,php,Php,在php中搜索字符串并找到不区分大小写的匹配项的最佳方法是什么 例如: $SearchString = "This is a test"; 从这个字符串中,我想找到单词test,或test或test 谢谢 编辑 我还应该提到,我想搜索字符串,如果它包含我的黑名单数组中的任何单词,停止处理它。因此,“Test”的精确匹配很重要,但是,我认为情况并非如此。大概它在找到匹配项时会停止搜索,我猜它会在内部转换为小写(或大写),所以这就可以了。我没有正确阅读问题。如其他答案所述,stripos或preg
$SearchString = "This is a test";
从这个字符串中,我想找到单词test,或test或test
谢谢
编辑
我还应该提到,我想搜索字符串,如果它包含我的黑名单数组中的任何单词,停止处理它。因此,“Test”的精确匹配很重要,但是,我认为情况并非如此。大概它在找到匹配项时会停止搜索,我猜它会在内部转换为小写(或大写),所以这就可以了。我没有正确阅读问题。如其他答案所述,stripos或preg_match函数将完全满足您的需求 我最初提供stristr函数作为答案,但如果您只是想在另一个字符串中查找字符串,实际上不应该使用它,因为它除了返回搜索参数外还返回字符串的其余部分。 取决于你是否想匹配 在这种情况下,您将执行以下操作:
$SearchString= "This is a test";
$pattern = '/[Test|TEST]/';
preg_match($pattern, $SearchString);
您可以做以下几件事中的一件,但我倾向于使用其中一件: 你可以用 您可以将字符串转换为一个特定的大小写,并使用 我两者都做,没有偏好——一个可能比另一个更有效率(我怀疑第一个更好),但我不知道 举几个更可怕的例子,你可以:
- 使用带有
修饰符的正则表达式i
- 执行
if(计数(explode('test',strtolower($searchString))>1)
if(preg_match("#\b{$needle}\b#i", $haystack))
{
return FALSE;
}
编辑,添加注释中要求的带字符转义的多字示例:
/* 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 */
}
正则表达式在这方面做得太过火了。实际上,我想搜索字符串,如果它包含我的黑名单数组中的任何单词,请停止处理它。如果您只需要精确(不区分大小写)匹配(例如“test”而不是“testing”),则Regex绝对是一种方法。我在服务器上进行了速度测试,花了1000次搜索[preg_match]=>0.0028190612792969[preg_match_与_b]=>0.0035979747772217[stristr]=>0.0051560401916504[stripos]=>0.0052568912506104[substr_count]=>0.005748987197876[strpos_和strtolower]=>0.0058009624481201[explode_和_count]=>0.0069141387939453由该代码生成:如果一些变量是URL的,我将如何处理?比如。我想扫描这个URL,看看它是否与我的黑名单中的test匹配。你需要转义的字符是:“[\^$。|?*+()”,可以用addcslashes($needle,[\^$。|?*+()”);嗨,帕根,谢谢你花时间来帮助我。我对RegEx几乎一无所知,你能给我一个我需要做什么的例子吗?目前我有一个代码,当我在服务器上测试时,在Pineder和haystack上使用strtolower比使用stripos慢9%
if(preg_match("#\b{$needle}\b#i", $haystack))
{
return FALSE;
}
/* 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 */
}