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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line