因為某些特殊原因,所以做了這兩個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
模糊
10 年前
1 意見:
分享去除條件範圍中的資料,保留條件範圍外的。
(如:$str = '<1><2>abcd<3><4>efg<5><6>
運算過後,留下
abcdefg)
function CatchStr($Str, $StaKey, $EndKey){
$explode_str = explode($StaKey , $Str);
//strpos : 尋找字串第一次出現的位置。
$StaPos = strpos($Str, $StaKey);
$EndPos = strpos($Str, $EndKey);
$i = 0;
foreach ( $explode_str as $e ){
if ( $i == 0 ){
//strlen : 字串長度。
$StaLen = strlen($StaKey);
$EndLen = strlen($EndKey);
//substr : 取得字串。
$CatchKey = substr($Str, $StaPos + $StaLen , $EndPos - $StaPos - $EndLen);
$OtherKeyA = substr($Str, 0, $StaPos);
$OtherKeyB = substr($Str, $EndPos + $EndLen);
}elseif(count($explode_str)-1 == $i){
}else{
$StaPos = strpos($new_str, $StaKey);
$EndPos = strpos($new_str, $EndKey);
//strlen : 字串長度。
$StaLen = strlen($StaKey);
$EndLen = strlen($EndKey);
//substr : 取得字串。
$CatchKey = substr($new_str, $StaPos + $StaLen , $EndPos - $StaPos - $EndLen);
$OtherKeyA = substr($new_str, 0, $StaPos);
$OtherKeyB = substr($new_str, $EndPos + $EndLen);
}
$new_str = $OtherKeyA.$OtherKeyB;
$i++;
}
//return array($new_str, $OtherKeyA, $OtherKeyB);
return $new_str;
}
張貼留言