2017-02-15 155 views
-1

我有兩個字符串abcbca。我想檢查一個其他字符串是否包含這兩個字符串,也不會重疊。例如:查找一個字符串有兩個重疊字符串PHP

  1. 一個字符串abca包含兩者但重疊。
  2. 一個字符串abcxbca包含並且不重疊。
  3. 一個字符串abcxbcabc包含兩個但重疊。
+4

那你試試這麼遠嗎?請在[MCVE](http://stackoverflow.com/help/mcve)後添加您的代碼 – peval27

回答

0

享受:)

<?php 

    $y1="abc"; //search string1 
    $y2="bca"; //search string2 

    $x1="abca"; //contains both but is overlapped. 
    $x2= "abcxbca"; //contains both and not overlapped. 
    $x3 ="abcxbcabc"; //contains both but is overlapped. 

    class Points{ 
    public $start; 
    public $stop; 
    public $overlaped=false; 

    private function Points($s1, $s2) { 
     $this->start=$s1; 
     $this->stop=$s2; 
     $this->overlaped=false; 
    } 


    public static function create($s1, $s2){ 
     if (is_numeric($s1)&&is_numeric($s2)){ 
      return new Points($s1, $s2); 
     } 
    else return NULL; 
    } 


} 

function display($arr){ 
    $cnt1=0; 
    $cnt2=0; 
    for ($i=0;$i<count($arr);$i++){ 
     if ($arr[$i]->overlaped===true) $cnt1++; 
     else $cnt2++; 
    } 

    return " ".$cnt2." not overlaped and ".$cnt1." overlaped"; 
} 

function strpos_all($haystack, $needle) { 
    $offset = 0; 
    $allpos = array(); 

    while (($pos = strpos($haystack, $needle, $offset)) !== FALSE) { 
     $offset = $pos + 1; 
     $allpos[] = Points::create($pos,$pos+strlen($needle)); 
    } 
    return $allpos; } 


    function check($haystack,$needle1,$needle2){ 

    $find1= strpos_all($haystack, $needle1); 

    $find2= strpos_all($haystack, $needle2); 



    for ($i=0;$i<count($find1);$i++){ 
     for($j =0; $j<count($find2);$j++){ 
      if (max($find1[$i]->start,$find2[$j]->start) <= min($find1[$i]->stop,$find2[$j]->stop)) { 
       $find1[$i]->overlaped=true; 
       $find2[$j]->overlaped=true; 
      } 
     } 
    } 

    echo $needle1.display($find1)."<br>"; 
    echo $needle2.display($find2)."<br>"; 

} 

echo "<br>------Start-------<br>"; 
echo "String :".$x1."<br>"; 
check ($x1,$y1,$y2); 
echo "<br>-----End----------<br>"; 

echo "<br>------Start-------<br>"; 
echo "String :".$x2."<br>"; 
check ($x2,$y1,$y2); 
echo "<br>-----End--------<br>"; 

echo "<br>------Start-------<br>"; 
echo "String :".$x3."<br>"; 
check ($x3,$y1,$y2); 
echo "<br>-----End--------<br>"; 

?>