Search code examples
phpregexpreg-replace-callback

php: preg_replace_callback remove detected content with its patterns


here is my string.

$string = '{TE:Hi}';

and this is my preg_replace_callback code:

echo preg_replace_callback('#(?<={TE:)(.*?)(?=})#is', function($matches){
        return '';
    }, $string);

i should use the preg_replace_callback because im using another function into callback function. this code can replace the detected content and remove it. but cant remove its patterns ( {TE: and } ) this only remove "Hi" from string but i want to remove "{TE:Hi}". "Hi" is dynamic and it can be something else. And there may be several patterns of this form in string.

thanks in advance.


Solution

  • If you want to remove the complete braced expression, then you should not use the (?<= nor (?= look-around. Just match:

    #{TE:(.*?)}#is
    

    Note that this will influence what is provided in the $matches array to the callback function.

    It will be ["{TE:Hi}", "Hi"] instead of ["Hi", "Hi"].