stristr return 仅匹配起始字符时的值?

stristr return value only if matching the starting characters?

stristr($haystack, $needle)

此函数将获取字符串 $haystack,通过它查找字符串 $needle,如果找到,将 return haystack 的整个值。

我想 return 只有当 $needle 从一开始就按顺序匹配任意数量的值时,我才想 return haystack 的值。

例如,stristr 将 return $haystack 在所有示例中,但我想要的是以下内容:

$haystack = "foo"
$needle =   "oo"
return false;

$haystack = "foo"
$needle =   "f"
return $haystack;

$haystack = "foo"
$needle =   "o"
return false;

$haystack = "foo"
$needle =   "fo"
return $haystack;

在我看来这可能是 php 中内置的东西,但我在文档中找不到任何东西。

谢谢。

您可以为此创建一个新函数并在其中使用 substrstrpos,例如:

function matchBegining($needle, $haystack)
{
    if(substr($haystack, 0, strlen($needle)) === $needle)
    {
        return $haystack;
    }
    return false;
}

如果匹配,这将 return $haystack,否则将 false

带有 strpos 的 if 语句:

 if (strpos($haystack, $needle) === 0) {