• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

php 搞代码 3年前 (2022-01-23) 20次浏览 已收录 0个评论
文章目录[隐藏]
$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@本文来源gaodai$ma#com搞$代*码6网搞代gaodaima码_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

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


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:菜鸟求教 如何循环替换文章中的附件标签
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址