Search code examples
phppreg-replacefile-existsbackreference

PHP - Using back references with file_exists in preg_replace


I am trying to replace content of some tags in included files with content from other files:

$view = preg_replace('/{include ([[:alnum:]\.-]+)}/', ((file_exists('template/$1.html')) ? 'OK $1' : 'KO $1'), file_get_contents('myTemplateFile.tpl'));

All the {include file.ext} references I got in myTemplateFile.tpl are replaced with KO file.ext instead of OK file.ext.

However, if I hardcode file_exists('template/file.ext'), then the right string is displayed.

It appears to me the back-reference is not correctly resolved inside the file_exists call.

What am I doing wrong?


Solution

  • preg_replace('/{include ([[:alnum:]\.-]+)}/', ((file_exists('template/$1.html')) ? 'OK $1' : 'KO $1'), file_get_contents('myTemplateFile.tpl'))
    

    This first executes file_exists('template/$1.html'), then passes OK $1 or KO $1 (likely the latter) to preg_replace, which then replaces all occurrences.

    You'll have to use a callback to make this work, not call file_exists as argument:

    preg_replace_callback(
        '/{include ([[:alnum:]\.-]+)}/',
        function (array $m) {
            return file_exists("template/$m[1].html") ? "OK $m[1]" : "KO $m[1]";
        },
        file_get_contents('myTemplateFile.tpl')
    )