仅当匹配起始字符时才返回stristr值?

问题描述:

stristr($haystack, $needle) 

该函数将采用字符串$ haystack,通过它查找字符串$针,如果找到将返回haystack的整个值。仅当匹配起始字符时才返回stristr值?

如果$ needle从头开始按顺序匹配任意数量的值,我只想返回haystack的值。

例如,stristr将返回$草垛在所有的例子,但我想下面是:

$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; 
} 

这将返回$haystack如果比赛和false如果没有。

if语句与strpos

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

表现似乎不错,谢谢! –