1
votes

When I run the below:

$MATH_REGEX = '/(?=(?<!\\)\$).(.+?)(?<!\\)\$/';
preg_replace_callback($MATH_REGEX, function ($match) {
        $latex_code = $match[0];
        return lx($latex_code); //lx is defined elsewhere
    }, "Test string $a=b$ .");

I get this:

$ php test.php
PHP Warning:  preg_replace_callback(): Compilation failed: missing ) at offset 26 in /home/sbird/public_html/faith/lib/view.php on line 26

What is wrong with my regex?

EDIT:

$ php --version
PHP 5.3.2-1ubuntu4.15 with Suhosin-Patch (cli) (built: May  4 2012 00:38:52) 
Copyright (c) 1997-2009 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
1
Can you add the original (unescaped) regex in your question? - buckley
Have you tried not using an anonymous function? - Ed Heal
@EdHeal what is wrong with anonymous functions? - wroniasty
@wroniasty - nothing - but sometimes useful to try without them in the first instance when you have a bug. - Ed Heal
that's true, although in this case it was pretty obvious the error had nothing to do with the lambda. - wroniasty

1 Answers

1
votes

You are escaping a (:

/(?=(?<!\\)\$).(.+?)(?<!\\)\$/
                 here:  ^^^

The resulting string passed to preg_replace_callback look like this:

php > $MATH_REGEX = '/(?=(?<!\\)\$).(.+?)(?<!\\)\$/';
php > echo $MATH_REGEX;
/(?=(?<!\)\$).(.+?)(?<!\)\$/
                       ^^ !!!