php 查找字符串中是否存在子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6937736/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:39:05  来源:igfitidea点击:

Find if substring exists in a string

phpregexstringsubstr

提问by bahamut100

I have a lot of strings, and I need to check if each of them contains a color.

我有很多字符串,我需要检查每个字符串是否包含颜色。

For example :

例如 :

  • A bird in the sky
  • 22 street of France
  • The dog is blue
  • The cat is black and white
  • 天空中的一只鸟
  • 法国22街
  • 狗是蓝色的
  • 猫是黑白的

So, the two last strings must return true.

因此,最后两个字符串必须返回 true。

What is the best way to find it?

找到它的最佳方法是什么?

Regex, or check with any substr() ?

正则表达式,或检查任何 substr() ?

回答by Quasdunk

I always work with strpossince it seems to be the fastest alternative (don't know about regex though).

我总是使用strpos它,因为它似乎是最快的替代方案(虽然不知道正则表达式)。

if(strpos($haystack, $needle) !== FALSE) return $haystack;

回答by Robin Castlin

In regexp you can write

在正则表达式中你可以写

preg_match_all("/(red|blue|black|white|etc)/", $haystack, $matches);

print_r($matches);

Use a loop for all the strings, and you'll easily notice which of the values from $matches you need.

对所有字符串使用循环,您将很容易注意到您需要 $matches 中的哪些值。

回答by Vipul jain

if you will use strpos then it returns a position of a string it will return a number 1,2,3 etc not true or false.

如果您将使用 strpos 那么它会返回一个字符串的位置,它将返回一个数字 1,2,3 等,而不是 true 或 false。

And the other problem is if string exist at the start it will return 0 which will consider as false then strpos cannot find that word.

另一个问题是,如果字符串在开头存在,它将返回 0,这将被视为 false,然后 strpos 找不到该单词。

回答by Tommy

strpos or strripos in php should be able to search for a single word in a string. You may have to loop in order to search for all colors if using it though

php 中的 strpos 或 strripos 应该能够搜索字符串中的单个单词。如果使用它,您可能必须循环才能搜索所有颜色