$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']);
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
谢啦,简短精辟的方法,太好用了。