如果我有两个PHP变量是字符串,一个是多字字符串,而另一个是单字字符串。
如何编写一个自定义函数,当较大字符串包含较小字符串时返回true。
这是目前为止我写的代码:
function contains($smaller, $larger){
//if $smaller is in larger{
return true;
}
else{
return false;
}
我怎么做注释掉的部分?
我不能使用正则表达式,因为我不知道$较小的确切值,对吗?
这个版本应该返回一个布尔值,并防止0和false返回
function contains($smaller, $larger){
return strpos($larger, $smaller) !== false;
}
有一个php函数strstr,它将返回"较小"字符串的位置。
http://www.php.net/manual/en/function.strstr.phpif(strstr($smaller, $larger))
{
//Its true
}
PHP已经有了。Strpos是你的答案
http://php.net/manual/en/function.strrpos.phpif (strpos($larger, $smaller) !== false){
// smaller string is in larger
} else {
// does not contains
}
如果找到字符串,则返回位置。注意检查是否为0(如果较小的位置在第0个位置)