PHP7 preg_replace 出錯(cuò)及解決辦法
問題描述:
PHP7廢棄了preg_replace?
原本是中php5中處理url中后面參數(shù)替換清除的,代碼如下
$url = preg_replace('/([?&])src=[^&]+(&?)/e', '"$2"==""?"":"$1"', $url);
但是到php7中就報(bào)錯(cuò)了
需要用preg_replace_callback來替換,請問該咋辦?
相關(guān)代碼
$url = preg_replace('/([?&])src=[^&]+(&?)/e', '"$2"==""?"":"$1"', $url);
問題分析:
e 修飾符因?yàn)榇嬖诎踩[患 自 5.3 開始就已經(jīng)標(biāo)記為了待移除的內(nèi)容。
轉(zhuǎn)而接替的是 preg_replace_callback,此方法第二個(gè)參數(shù)為一個(gè)回調(diào)函數(shù),回調(diào)函數(shù)會自動傳入比配的分組作為參數(shù)。在回調(diào)函數(shù)內(nèi)部通過數(shù)組下標(biāo)訪問匹配組。(手機(jī)碼字 未格式化代碼)
preg_replace_callback('/([?&])src=[^&]+(&?)/', function($matches){ return $matches[2]==""?"":$matches[1]; }, $url);
知識點(diǎn)擴(kuò)展:
PHP7已經(jīng)刪除了preg_replace的e修飾符
官網(wǎng)提示是這樣的,對/e修飾符的支持已刪除。請改用preg_replace_callback()
原因是/e 修正符使 preg_replace() 將 replacement 參數(shù)當(dāng)作 PHP 代碼(在適當(dāng)?shù)哪嫦蛞锰鎿Q完之后),會被一句話后門使用
看看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模板修改成這個(gè) $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);
到此這篇關(guān)于PHP7 preg_replace 出錯(cuò)及解決辦法的文章就介紹到這了,更多相關(guān)PHP7 preg_replace 使用出錯(cuò)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PHP中對緩沖區(qū)的控制實(shí)現(xiàn)代碼
在PHP 4.0里面加入了緩沖區(qū)控制的幾個(gè)函數(shù),使用這些函數(shù)可以幫我們解決很多問題2013-09-09PHP 5.5 創(chuàng)建和驗(yàn)證哈希最簡單的方法詳解
最近 PHP 5.5.0 發(fā)布了,并帶來了一份完整的全新特性與函數(shù)的列表。全新API之一就是Password Hashing API.它包含4個(gè)函數(shù):password_get_info(), password_hash(), password_needs_rehash(),和password_verify().讓我們分步來了解每個(gè)函數(shù)2013-11-11php 中獎(jiǎng)概率算法實(shí)現(xiàn)代碼
這篇文章主要介紹了php 中獎(jiǎng)概率算法,需要的朋友可以參考下2017-01-01php+dojo 的數(shù)據(jù)庫保存拖動布局的一個(gè)方法dojo 這里下載
php+dojo 的數(shù)據(jù)庫保存拖動布局的一個(gè)方法dojo 這里下載...2007-03-03php實(shí)現(xiàn)的Curl封裝類Curl.class.php用法實(shí)例分析
這篇文章主要介紹了php實(shí)現(xiàn)的Curl封裝類Curl.class.php用法,以完整實(shí)例形式較為詳細(xì)的分析了Curl封裝類的定義及相關(guān)使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-09-09