Search code examples
phppreg-replacepreg-replace-callback

PHP preg_replace_callback


I have this tag into my html file:

    {{block:my_test_block}} 
{{news:my_test_block2}}

I need to parse and replace this tag with content from db, my aproach:

     ob_start();
     require_once('file.php');
     $template = ob_get_contents();
     ob_end_clean();

      $line = preg_replace_callback('/{(\w+)}/' , "parseTag" , $template);

function parseTag($matches){
   //here switch for block, news, 
}

is it the right way? Thanks.


Solution

  • Try use

    '/{{(.+):(.+)}}/'
    

    So in the $matches[1] you will see the block or news.

    Your script shall look like that

    $line = preg_replace_callback('/{{(.+):(.+)}}/' , "parseTag" , $template);
    
    function parseTag($matches){
       if($matches[1] == 'block'){
            $return = 'Its Blocked';
       }elseif($matches[1] == 'news'){
            $return = 'Great news';
       }else{
            $return = 'Ops...';
       }
       return $return;
    }