在某个位置之前查找第一次出现的子串

时间:2013-09-10 22:15:29

标签: php strpos

在PHP中,如果我有一个长字符串,IE 10'000字符,你会怎么建议我在给定位置之前和之后找到某个字符串的第一个出现。

IE,如果我有字符串:

BaaaaBcccccHELLOcccccBaaaaB

我可以使用strpos来找到HELLO的位置。那么我怎样才能找到HELLO之前B的第一次出现的位置以及HELLO之后B的第一次出现?

3 个答案:

答案 0 :(得分:1)

您可以使用stripos()和strripos()查找字符串中子字符串的首次出现。您也可以为strripos()函数提供负偏移量,以相反的顺序搜索(从右到左)。 strripos() with negative offset

$body = "BaaaaBcccccHELLOcccccBaaaaB";
$indexOfHello = stripos($body, 'Hello');
if ($indexOfHello !== FALSE)
{
    // First Occurrence of B before Hello
    $indexOfB= stripos(substr($body,0,$indexOfHello),'B',($indexOfHello * -1));
    print("First Occurance of B before Hello is ".$indexOfB."\n") ;
    
    // First Occurrence of B before Hello (in reverse order)
    $indexOfB= strripos($body,'B',($indexOfHello * -1));
    print("First Occurrence of B before Hello (in reverse order) is ".$indexOfB."\n") ;
    
    // First Occurrence of B after Hello
    $indexOfB= stripos($body,'B',$indexOfHello);
    print("First Occurance of B after Hello is ".$indexOfB."\n") ;
}

答案 1 :(得分:0)

鉴于这个职位......

要查找之前的第一个匹配项,您可以在匹配前选择substr()并使用strrpos()

要查找之后的第一个匹配项,您仍然可以使用strpos()并设置偏移参数。

答案 2 :(得分:0)

如果您考虑优化,那么会有很多pattern search algorithms

这是朴素模式搜索的示例:

/**
 * Naive algorithm for Pattern Searching
*/
function search(string $pat, string $txt, int $searchFrom = 0, ?int $searchTill = null) 
{ 
    $M = strlen($pat); 
    $N = strlen($txt); 

    if ($searchTill !== null && $searchTill < $N){
        $N = $searchTill;
    }

    for ($i = $searchFrom; $i <= $N - $M; $i++) 
    { 
  
        // For current index i,  
        // check for pattern match  
        for ($j = 0; $j < $M; $j++) 
            if ($txt[$i + $j] != $pat[$j]) 
                break; 
  
        // if pat[0...M-1] =  
        // txt[i, i+1, ...i+M-1] 
        if ($j == $M)  
            return $i;
    } 
} 

// Driver Code 
$txt = "BaaaaBcccccHELLOcccccBaaaaB"; 
if (null!==($helloPos = search("HELLO", $txt))){

    print("First Occurance of B before Hello is ".search("B", $txt, 0, $helloPos)."<br>") ;
    print("First Occurance of B after Hello is ".search("B", $txt, $helloPos, null)."<br>") ;
}
相关问题