简体   繁体   English

PHP-如何测试字符串是否包含大写单词?

[英]php - how to test if a string contains an uppercase word?

$string = "ttest test NEEDLE haystack"; $ string =“ ttest测试NEEDLE干草堆”;

How do I match to see if the $string contains the uppercase word "NEEDLE"? 如何匹配以查看$ string是否包含大写单词“ NEEDLE”?

I have been using if ( stristr($string, 'NEEDLE') === TRUE ) but it is not case sensitive. 我一直在使用if ( stristr($string, 'NEEDLE') === TRUE )但是它不区分大小写。

TIA TIA

Just use strstr instead 只需使用strstr代替

if ( strstr($string, 'NEEDLE') === TRUE )

However: this will still fail, because the strstr function and stristr return a string and only a boolean, if the sub-string is not found. 但是:这仍然会失败,因为如果找不到子字符串,则strstr函数和stristr返回一个字符串,并且仅返回一个布尔值。 You could also use strpos instead, which returns either an integer or false, if the substring was not found: 如果找不到子字符串,也可以使用strpos,它返回整数 false:

if (strpos($string, 'NEEDLE') !== false)

You can use the function strstr , which is the case-sensitive version of stristr : 您可以使用功能strstr ,它是stristr的区分大小写的版本:

if ( strstr($string, 'NEEDLE') !== false ) {
  // do something...
}

Note that strstr documentation recommends using strpos if you just only want to know if the needle occurs within the haystack. 请注意,如果您仅想知道针是否在干草堆中,则strstr文档建议使用strpos

If you need more complex comparisons you could also use preg_match , but in this case I think strstr is enough. 如果需要更复杂的比较,也可以使用preg_match ,但是在这种情况下,我认为strstr就足够了。

Use the case-sensitive strpos : 使用区分大小写的strpos

if (strpos($string, 'NEEDLE') !== false)

strstr would work as well here, but unnecessarily returns the rest of the string instead of just a short indication where it has been matched. strstr在这里也可以工作,但是不必要地返回字符串的其余部分,而不仅仅是返回已匹配的简短指示。 Note that neither of stristr , strstr , or strpos ever return true . 请注意, stristrstrstrstrpos都不会返回true

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

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