dongzhao4036 2013-08-13 21:26
浏览 40
已采纳

PHP:使用preg_match_all创建对象并调用对象函数[重复]

This question already has an answer here:

I'm trying to use preg_match_all to find instances of a pattern in text, then use that pattern to instantiate a class and finally call a class function to print replacement text for the matching pattern. I don't know if I'm going about it the right way.

I can find and replace this pattern [bandcamp=http://bandcamp-page.com]1[/bandcamp] with this preg_replace function

$text = preg_replace ("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", "replacement text here", $text);

But I want to use the matches to create a BandcampAlbum object and call it's player() function which prints out html. This is what I'm trying but to no avail so far.

if (preg_match_all ("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", $text, $matches)) {

    foreach ($matches[0] as $match) {
        preg_replace ("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", "", $text);
        $bc = new BandcampAlbum($match[0], $match[1]);
        $bc->player();
    }

}

The preg_replace in the foreach loop is intended to just get rid of the matching text. The matching seems to work so I'm guessing I'm doing it the wrong way rather than making a regular expression error. Any suggestions welcome.

</div>
  • 写回答

1条回答 默认 最新

  • douxian6008 2013-08-14 16:38
    关注

    As stated in the comments; what you are probably after is preg_replace_callback. Here is an example of its usage with your problem:

    function getBandCampMarkup($matches){
        $bc = new BandcampAction($matches[1], $matches[2]);
        return $bc->player();
    }
    
    $data = preg_replace_callback("/\[bandcamp=(.+?)\](.+?)\[\/bandcamp\]/", "getBandCampMarkup", $data);
    echo $data;
    

    This is of course assuming the $bc->player() returns a string of the output. If this function just echos the data then you can can use ob_start and ob_get_clean to capture the output as a string as so:

    ob_start();
    $bc->player();
    return ob_get_clean();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题
  • ¥30 seata使用出现报错,其他服务找不到seata
  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?