Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
343 views
in Technique[技术] by (71.8m points)

php - 如何检查字符串是否包含特定单词?(How do I check if a string contains a specific word?)

Consider:

(考虑:)

$a = 'How are you?';

if ($a contains 'are')
    echo 'true';

Suppose I have the code above, what is the correct way to write the statement if ($a contains 'are') ?

(假设我有上面的代码, if ($a contains 'are') ,写语句的正确方法if ($a contains 'are')什么?)

  ask by community wiki translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the strpos() function which is used to find the occurrence of one string inside another one:

(您可以使用strpos()函数来查找另一个字符串中另一个字符串的出现:)

$a = 'How are you?';

if (strpos($a, 'are') !== false) {
    echo 'true';
}

Note that the use of !== false is deliberate (neither != false nor === true will return the desired result);

(注意, !== false的使用是有意的( != false=== true都不会返回期望的结果)。)

strpos() returns either the offset at which the needle string begins in the haystack string, or the boolean false if the needle isn't found.

(strpos()返回大海捞针字符串中针串开始的偏移量,或者如果找不到针,则返回布尔值false 。)

Since 0 is a valid offset and 0 is "falsey", we can't use simpler constructs like !strpos($a, 'are') .

(由于0是一个有效的偏移量,而0是“ falsey”,我们不能使用更简单的结构,例如!strpos($a, 'are') 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...