0

如果我有两个 PHP 变量是字符串,一个是多字字符串,另一个是单字字符串。

如果较大的字符串包含较小的字符串,我如何编写一个返回 true 的自定义函数。

这是我到目前为止在代码方面的内容:

function contains($smaller, $larger){
    //if $smaller is in larger{
        return true;
    }
    else{
         return false;

}

我该如何做注释掉的部分?

我不能使用正则表达式,因为我不知道 $smaller 的确切值,对吧?

4

3 回答 3

2

有一个 php 函数 strstr 将返回“较小”字符串的位置。

http://www.php.net/manual/en/function.strstr.php

if(strstr($smaller, $larger)) 
{
     //Its true
}
于 2013-06-07T21:42:06.477 回答
2

PHP 已经有了。Strpos 是您的答案

http://php.net/manual/en/function.strrpos.php

if (strpos($larger, $smaller) !== false){
  // smaller string is in larger
} else {
  // does not contains
}

如果找到该字符串,则返回该位置。注意检查 0(如果较小的位置在第 0 个位置)

于 2013-06-07T21:45:21.433 回答
2

此版本应返回布尔值并防止 0 与错误返回

function contains($smaller, $larger){
   return strpos($larger, $smaller) !== false;
}
于 2013-06-07T21:57:05.423 回答