php 在字符串中查找确切的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16283837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find exact string inside a string
提问by Tudor Ravoiu
I have two strings "Mures" and "Maramures". How can I build a search function that when someone searches for Mures it will return him only the posts that contain the "Mures" word and not the one that contain the "Maramures" word. I tried strstr until now but it does now work.
我有两个字符串“Mures”和“Maramures”。我怎样才能建立一个搜索功能,当有人搜索 Mures 时,它只会返回包含“Mures”字样的帖子而不是包含“Maramures”字样的帖子。直到现在我都尝试过 strstr 但它现在可以工作了。
回答by Crayon Violent
You can do this with regex, and surrounding the word with \b
word boundary
你可以用正则表达式来做到这一点,并\b
用词边界包围这个词
preg_match("~\bMures\b~",$string)
preg_match("~\bMures\b~",$string)
example:
例子:
$string = 'Maramures';
if ( preg_match("~\bMures\b~",$string) )
echo "matched";
else
echo "no match";
回答by Brucee
Use preg_match function
使用 preg_match 函数
if (preg_match("/\bMures\b/i", $string)) {
echo "OK.";
} else {
echo "KO.";
}
回答by rekire
How do you check the result of strstr? Try this here:
你如何检查strstr的结果?在这里试试这个:
$string = 'Maramures';
$search = 'Mures';
$contains = strstr(strtolower($string), strtolower($search)) !== false;
回答by North
Maybe it's a dumb solution and there's a better one. But you can add spaces to the source and destination strings at the start and finish of the strings and then search for " Mures ". Easy to implement and no need to use any other functions :)
也许这是一个愚蠢的解决方案,但有一个更好的解决方案。但是您可以在字符串的开头和结尾为源字符串和目标字符串添加空格,然后搜索“Mures”。易于实现,无需使用任何其他功能:)
回答by Liv
You can do various things:
你可以做各种事情:
- search for ' Mures ' (spaces around)
- search case sensitive (so 'mures' will be found in 'Maramures' but 'Mures' won't)
- use a regular expression to search in the string ( 'word boundary + Mures + word boundary') -- have a look at this too: Php find string with regex
- 搜索“Mures”(周围有空格)
- 搜索区分大小写(所以 'mures' 将在 'Maramures' 中找到,但 'Mures' 不会)
- 使用正则表达式在字符串中搜索(“词边界 + Mures + 词边界”)——也看看这个:Php find string with regex
回答by brbcoding
function containsString($needle, $tag_array){
foreach($tag_array as $tag){
if(strpos($tag,$needle) !== False){
echo $tag . " contains the string " . $needle . "<br />";
} else {
echo $tag . " does not contain the string " . $needle;
}
}
}
$tag_array = ['Mures','Maramures'];
$needle = 'Mures';
containsString($needle, $tag_array);
A function like this would work... Might not be as sexy as preg_match
though.
像这样的功能会起作用......可能没有那么性感preg_match
。
回答by Atanas Beychev
The very simple way should be similar to this.
非常简单的方法应该与此类似。
$stirng = 'Mures';
if (preg_match("/$string/", $text)) {
// Matched
} else {
// Not matched
}