Home >Backend Development >PHP Tutorial >初学者求教 怎么循环替换文章中的附件标签

初学者求教 怎么循环替换文章中的附件标签

WBOY
WBOYOriginal
2016-06-13 12:24:06871browse

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

本帖最后由 qq33184 于 2015-09-06 00:32:33 编辑
<br />$article['content'] = str_replace('[attach_40]', $this->get_attach_url('40'), $article['content']);<br />$article['content'] = str_replace('[attach_41]', $this->get_attach_url('41'), $article['content']);<br />$article['content'] = str_replace('[attach_42]', $this->get_attach_url('42'), $article['content']);<br /><br />替换规则<br />$article['content'] = preg_replace('/\[attach_(\d+)\]/is', $this->get_attach_url('\1'), $article['content']);<br />


说明:
$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