Home > Backend Development > PHP7 > PHP7 preg_replace is wrong when used?

PHP7 preg_replace is wrong when used?

藏色散人
Release: 2023-02-18 09:06:01
forward
1694 people have browsed it

本篇文章由PHP7教程栏目给大家介绍一下关于 PHP7 使用preg_replace出错的问题。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

问题描述:

PHP7废弃了preg_replace?

原本是中php5中处理url中后面参数替换清除的,代码如下

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

但是到php7中就报错了

需要用preg_replace_callback来替换,请问该咋办?

相关代码

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

问题分析:

e 修饰符因为存在安全隐患 自 5.3 开始就已经标记为了待移除的内容。

转而接替的是 preg_replace_callback,此方法第二个参数为一个回调函数,回调函数会自动传入比配的分组作为参数。在回调函数内部通过数组下标访问匹配组。(手机码字 未格式化代码)

preg_replace_callback('/([?&])src=[^&]+(&?)/', function($matches){
    return $matches[2]==""?"":$matches[1];
}, $url);
Copy after login

The above is the detailed content of PHP7 preg_replace is wrong when used?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template