Home >Backend Development >PHP Tutorial >菜鸟求教 如何循环替换文章中的附件标签

菜鸟求教 如何循环替换文章中的附件标签

WBOY
WBOYOriginal
2016-06-20 12:49:13910browse

$article['content'] = str_replace('[attach_40]', $this->get_attach_url('40'), $article['content']);$article['content'] = str_replace('[attach_41]', $this->get_attach_url('41'), $article['content']);$article['content'] = str_replace('[attach_42]', $this->get_attach_url('42'), $article['content']);替换规则$article['content'] = preg_replace('/\[attach_(\d+)\]/is', $this->get_attach_url('\1'), $article['content']);


说明:
$article['content'] 文章内容
[attach_42] 附件标签 其中数字是改附件在数据表中的ID
get_attach_url()方法可以获得附件的完整路径 如:http://127.0.0.10/attach/2015-09-05/1441449289kWkS.jpg

菜鸟求教 如何循环替换文章中的附件标签


回复讨论(解决方案)

php5.5 以下可以
$article['content'] = preg_replace('/\[attach_(\d+)\]/ise', '$this->get_attach_url("\1")', $article['content']);

所有版本都可以
$article['content'] = preg_replace_callback('/\[attach_(\d+)\]/is', array($this, 'get_attach_url'), $article['content']);
但需要修改 get_attach_url 方法(单值参数改数组参数)

php5.4及以上还可以
$article['content'] = preg_replace('/\[attach_(\d+)\]/is', function($m) { return $this->get_attach_url($m[1]; }, $article['content']);
php5.3 虽然已经支持闭包,但闭包中不能使用 $this


谢啦,简短精辟的方法,太好用了。

Statement:
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
Previous article:关于curl的问题Next article:关于php访问控制的问题