简体   繁体   English

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

[英]Find if substring exists in a string

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 法国22街
  • The dog is blue 狗是蓝色的
  • The cat is black and white 猫是黑色和白色

So, the two last strings must return true. 因此,最后两个字符串必须返回true。

What is the best way to find it? 找到它的最佳方法是什么?

Regex, or check with any substr() ? 正则表达式,或检查任何substr()?

我总是使用strpos因为它似乎是最快的选择(虽然不知道正则表达式)。

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

In regexp you can write 在regexp中你可以写

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. 对所有字符串使用循环,您将很容易注意到您需要的$匹配值。

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,这将被认为是假,然后strpos无法找到该字。

strpos or strripos in php should be able to search for a single word in a string. php中的strpos或strripos应该能够在字符串中搜索单个单词。 You may have to loop in order to search for all colors if using it though 如果使用它,您可能必须循环才能搜索所有颜色

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM