Jump to content

preg_replace_callback and highlight_string inside variable

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
5 replies to this topic

#1
webcodez

webcodez

    Programmer

  • Members
  • PipPipPipPip
  • 149 posts
Hi there,

Having a problem with the following code I created:

$new_reply = preg_replace_callback("/[CODE](.*)[CODE]/", create_function('$matches', 'return highlight_string($matches[1], 1);'), $new_reply);

What it's supposed to do is replace for example [ CODE ] some text [ / CODE ] by highlight_string("some text") (returning that text highlighted to the variable $new_reply).

Why aint it working? Any suggestions?

Thanks in advanced~!

Cheers.

Edited by John, 09 April 2010 - 09:35 PM.


#2
webcodez

webcodez

    Programmer

  • Members
  • PipPipPipPip
  • 149 posts
Anyone?

#3
Guest_Jaan_*

Guest_Jaan_*
  • Guests
I don't think it works like this:D
don't use ' and '

#4
webcodez

webcodez

    Programmer

  • Members
  • PipPipPipPip
  • 149 posts
Eh, just done it accordingly to: PHP: preg_replace_callback - Manual >_<

#5
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
Don't listen to Jaan, like usual, he doesn't know what he is talking about. Nice use of lambda-style functions. However, square brackets are used as special characters (which define a character class). If you wish to use them as a "regular" character to match on, you must escape them.

<?php

$new_reply = "[CODE]test[/CODE]";

echo "Before: " . $new_reply . "\n";

$new_reply = preg_replace_callback("/\[CODE\](.*)\[\/CODE\]/", create_function('$matches', 'return highlight_string($matches[1], 1);'), $new_reply);

echo "After: " . $new_reply . "\n";

?>


john@mars [~]# php test.php

Before: [CODE]test[/CODE]

After: <code><span style="color: #000000">

test</span>

</code>



#6
webcodez

webcodez

    Programmer

  • Members
  • PipPipPipPip
  • 149 posts
Ah yeah that should do it, great! Thanks a lot for your help. Encountered same problem with other regular expressions ( did not escape the brackets ) which are fixed too now =].