preg_replace with function

吃可爱长大的小学妹 提交于 2019-12-22 16:33:57

问题


I have some HTML that is being run through PHP:

<a href="?char=">&</a>

and I'm wanting to use a preg_replace to replace the first & with a urlencoded value of it. However:

preg_replace("/char=\">(.*?)<\/a>/", "char=".urlencode("$1")."\">$1</a>", $links);

But this gives me the value $1, instead of the expected back-reference. How can I do what I'm trying to do (make the output look like <a href="?char=%26">&</a>)?


回答1:


You can use the modifier e in your regexp or use the function preg_replace_callback (see the doc) instead.




回答2:


Yes, both e modifier and preg_replace_callback function approaches can do the job.
I personally prefer one-line decision:

preg_replace("/char=\">(.*?)</a>/e", '"char=".urlencode("$1")."\\">$1"', $links);



来源:https://stackoverflow.com/questions/1710764/preg-replace-with-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!