2009年11月3日 星期二

[PHP]指定範圍字串擷取、字串(數字)範圍判斷

因為某些特殊原因,所以做了這兩個FUNCTION.....

◎可以在字串中取出兩特定關鍵字內的字串

function CatchStr($Str, $StaKey, $EndKey){
 $StaPos = strpos($Str, $StaKey);
 $EndPos = strpos($Str, $EndKey);
 $StaLen = strlen($StaKey);
 $EndLen = strlen($EndKey);

 $CatchKey = substr($Str, $StaPos + $StaLen , $EndPos - $StaPos - $EndLen);
 $OtherKeyA = substr($Str, 0, $StaPos);
 $OtherKeyB = substr($Str, $EndPos + $EndLen);

 return array($CatchKey, $OtherKeyA, $OtherKeyB);
}


CatchStr(字串, 開頭關鍵字, 結尾關鍵字)

例:
$Str = "ABCDE{1234567890}FGHIJK";
$StrArray = CatchStr($Str, "{", "}");
結果:
$StrArray[0] = 1234567890
$StrArray[1] = ABCDE
$StrArray[2] = FGHIJK



◎可以判斷把字串中數字做範圍比較


function SearchNum($Str, $Target, $CountSym = ",", $ToSym = "-"){
 $StrArray = explode($CountSym, $Str);

 foreach ($StrArray as &$value) {
  if (strpos($value, $ToSym)) {
   $VarArray = explode($ToSym, $value);
   if ($VarArray[0] <= $Target && $Target <= $VarArray[1]){
    $Touch = "true";
   }else{
    $Touch = "false";
   }
  }else{
   if ($value == $Target){
    $Touch = "true";
   }else{
    $Touch = "false";
   }
  }
 }
 return $Touch;
}

SearchNum(字串, 欲尋找的目標數值, 每筆資料的分隔符號(預設 , ), 連續資料的連接符號(預設 - ))

例:
$Str = "1,2,3,4,5,6-10,11,12,13";
$StrAns = SearchNum($Str, 8);
結果:
$StrAns = "true"


例:
$Str = "1,2,3,4,5,6,10,11,12,13";
$StrAns = SearchNum($Str, 8);
結果:
$StrAns = "false"



其實這兩個Function還沒有很完美,
CatchStr()還不能判斷字串中有多個關鍵符號,目前只能取第一次出現的關鍵符號。
SearchNum()還不能判斷連續數字的大小順序,只能由小到大判斷。

以後有空在改版~ :P

##EasyReadMore##