Jump to content

Putting a function within 'preg_replace'


GuitarGod

Recommended Posts

Hi,

 

I'm trying to create a simple BB code-type function, but I'm having trouble putting a function within preg_replace. Let me show you what I mean:

 

$bb_search = array
      (
            '/\[b\]/',
            '/\[\/b\]/',
            '/\[img\=(.*?)\]/',
      );

      $bb_replace = array
      (
            '<b>',
            '</b>',
            check_image( '\\1' ),
      );

      return preg_replace( $bb_search, $bb_replace, $text_string );

 

The first two (b and /b) work fine, even the function is recognised, but using \\1 doesn't put the bbcode value as the function value. I know that probably made no sense - I'm terrible at explaining these things, so sorry. If anyone can understand what I mean, even offer a solution, that would be great!

 

Cheers! :D

Link to comment
https://forums.phpfreaks.com/topic/219217-putting-a-function-within-preg_replace/
Share on other sites

Note that there's a comment on the manual page for preg_replace_callback that basically parses bbcode output recursively.

 

-Dan

 

You probably want to use the e modifier since you only want one pattern to hit the function, not all:

 

$bb_search = array
      (
            '/\[b\]/',
            '/\[\/b\]/',
  // add e modifier to have the replacement evaluated as PHP code
            '/\[img\=(.*?)\]/e',
      );

$bb_replace = array
      (
            '<b>',
            '</b>',
// quote the function or else it will be called when you define the array not on replacement
            'check_image("\\1")',
      );

try

<?php
$bb_search = array
      (
            '/\[b\]/',
            '/\[\/b\]/',
            '/\[img\=(.*?)\]/e',
      );

      $bb_replace = array
      (
            '<b>',
            '</b>',
            'check_image( \\1 )'
      );
$test = '[img=sasa]';
function check_image($a){
    return "<img src='$a'>";
}
echo preg_replace($bb_search, $bb_replace, $test);

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.