为什么 PHP 没有简单的包含字符串函数?

Why doesn't PHP have a simple contains string function?

我很好奇为什么 "contains" 的论坛在 PHP 里这么复杂?

我正在学习 PHP 来自一种不太常用的语言,叫做 Lasso。 PHP 和 Lasso 非常相似。

Lasso 有一个非常好的东西是包含字符串函数 >>

if($myVar >> 'x')  // this is a contains statement

有没有比以下更简单的方法:

if(strpos($a, 'are') !== false)

这几乎像是一个双重否定。为什么不 == 真的?这可能是我遇到过的最令人困惑的事情。我希望有人能给出一些启示!

编辑:我认为我的问题的答案是没有其他快捷方式代码包含。感谢大家的帮助。

正如文档所说:

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.

Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

你不能做 == true 因为 strpos 可以 return 0 如果字符串出现在第 0 个索引处(即字符串的最开头),这将导致 == true 检查失败,因为 0 是一个错误的 y 值。

TL;DR: strpos 不是 "contains" 函数,它是一个 "what's the position of the string" 函数,可以 使用 作为 "contains" 函数作为结果。

需要注意的是strpos会对包含__toString()方法的对象进行字符串转换

比如这个

    //Enter your code here, enjoy!

class foo{

    public function __toString(){
        return 'hello world';
    }
}

$Foo = new foo;

echo strpos($Foo, "world");

输出

6

当然,在这种情况下,这种情况确实不太可能发生,但我认为值得一提。

如图所示 sandbox