2012-05-28 34 views
4

我數了數的一些特殊的字符(如歐元符號)在$text,使用preg_match_all和正則表達式:爲什麼preg_match_all迫使我提供第三個可選參數?

preg_match_all('/[\[|\]|€\{|}|\\|\^|\||~]/u', $text); 

一些奇怪的原因PHP問我第三個參數。但它應該是可選的documentation of preg_match_all

警告:preg_match_all()期望至少3個參數,給出2。

如果我提供PREG_PATTERN_ORDER(甚至不知道我爲什麼)我得到:

不能按引用傳遞參數3。

那麼,我的代碼有什麼問題?如果需要,以下是整個功能:

public function getMessageCount($text) 
{ 
    $specials = preg_match_all('/[\[|\]|€\{|}|\\|\^|\||~]/u', $text) 
    $characters = strlen($text) + $specials; 

    if(in_array(strtolower($this->method), self::$classic_plans)) : 

     if($characters >= 0 && $characters <= 160) return 1; 
     if($characters >= 161 && $characters <= 306) return 2; 
     if($characters >= 307 && $characters <= 459) return 3; 
     if($characters >= 460 && $characters <= 612) return 4; 

     return 5; 

    endif; 

    if(in_array(strtolower($this->method), self::$basic_plans)) : 

     if($characters >= 0 && $characters <= 160) return 1; 
     if($characters >= 161 && $characters <= 312) return 2; 
     if($characters >= 313 && $characters <= 468) return 3; 
     if($characters >= 469 && $characters <= 624) return 4; 
     if($characters >= 625 && $characters <= 780) return 5; 
     if($characters >= 781 && $characters <= 936) return 6; 
     if($characters >= 937 && $characters <= 1092) return 7; 
     if($characters >= 1093 && $characters <= 1248) return 8; 

     return 9; 

    endif; 

    return in_array(strtolower($this->method), self::$zero_plans) ? 1 : null; 
} 

回答

4

雖然第三個參數在5.4.0起成爲可選項喜歡別人已經說過,但如果你通過第三個參數你的代碼甚至不編譯,因爲你說你通過PREG_PATTERN_ORDER國旗,但第三個參數應該是數組接收匹配和第四個參數是標誌。

使用類似的following

<?php 
$dummy = array(); 
echo("Result = ".preg_match_all('/[\[|\]|x\{|}|\\|\^|\||~]/', $text, $dummy)); 
?> 
1

查看您提供的鏈接中的更改日誌。之後,檢查您的PHP版本;)

+0

即'5.4.0 \t的匹配參數成爲optional.' –

2

它從PHP 5.4.0變成了可選項。參數成爲可選

更新日誌

5.4.0比賽。

1

返回值preg_match_all是一個int →匹配數。匹配文本將填入參數的3 rd參數中。

// incorrect 
$specials = preg_match_all('/[\[|\]|€\{|}|\\|\^|\||~]/u', $text);  

// correct 
$num = preg_match_all('/[\[|\]|€\{|}|\\|\^|\||~]/u', $text, $specials); 
相關問題