PHP7 preg_replace 出錯及解決辦法

問題描述:

PHP7廢棄了preg_replace?

原本是中php5中處理url中後面參數替換清除的,代碼如下

1
$url = preg_replace( '/([?&])src=[^&]+(&?)/e' , '"$2"==""?"":"$1"' , $url );

但是到php7中就報錯了

需要用preg_replace_callback來替換,請問該咋辦?

相關代碼

1
$url = preg_replace( '/([?&])src=[^&]+(&?)/e' , '"$2"==""?"":"$1"' , $url );

問題分析:

e 修飾符因爲存在安全隱患 自 5.3 開始就已經標記爲了待移除的內容。

轉而接替的是 preg_replace_callback,此方法第二個參數爲一個回調函數,回調函數會自動傳入比配的分組作爲參數。在回調函數內部通過數組下標訪問匹配組。(手機碼字 未格式化代碼)

1
2
3
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中是也是這樣用的,也是存在問題

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$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 );

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章