PHP7廢棄了preg_replace?
原本是中php5中處理url中后面參數替換清除的,代碼如下
$url?=?preg_replace('/([?&])src=[^&]+(&?)/e',?'"$2"==""?"":"$1"',?$url);
但是到php7中就報錯了
需要用preg_replace_callback來替換,請問該咋辦?
相關代碼
$url?=?preg_replace('/([?&])src=[^&]+(&?)/e',?'"$2"==""?"":"$1"',?$url);問題分析:
e修飾符因為存在安全隱患 自 5.3 開始就已經標記為了待移除的內容。
轉而接替的是 preg_replace_callback,此方法第二個參數為一個回調函數,回調函數會自動傳入比配的分組作為參數。在回調函數內部通過數組下標訪問匹配組。
preg_replace_callback('/([?&])src=[^&]+(&?)/',?function($matches){ ????return?$matches[2]==""?"":$matches[1]; },?$url);
知識點擴展:
PHP7已經刪除了preg_replace的e修飾符
官網提示是這樣的,對/e修飾符的支持已刪除。請改用preg_replace_callback()
原因是/e 修正符使 preg_replace() 將 replacement 參數當作 PHP 代碼(在適當的逆向引用替換完之后),會被一句話后門使用
看看smarty中是也是這樣用的,也是存在問題
$source_content?=?preg_replace($search.'e',?"'" .?$this->_quote_replace($this->left_delimiter)?.?'php' .?"'?.?str_repeat(\"\n\",?substr_count('\\0',?\"\n\"))?.'" .?$this->_quote_replace($this->right_delimiter) .?"'" ,?$source_content); 可以把smarty模板修改成這個 $source_content?=?preg_replace_callback($search,?function?($matches){ $str=""; $str.=$this->_quote_replace($this->left_delimiter)?.?'php'; $str.=str_repeat("\\n\\",?substr_count($matches[1],?"\\n\\")); $str.=$this->_quote_replace($this->right_delimiter); return?$str; },?$source_content);
到此這篇關于PHP7 preg_replace 出錯及解決辦法的文章就介紹到這了,希望大家以后多多支持好二三四!