Jump to content

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);

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.