1

So I tried to get this backreferences to work, but I can't figure it out for the life of me.

Currently I have this string <% size_../files/file.rar %> and I need to replace it with the actual file size.

This is what I have so far.

$oldStr = "<% size_../files/file.rar %>";
$newStr = preg_replace("/<% size_(\w+) %>/", filesize("$1"), $oldStr);

Basically I need to get the pattern (\w+) and use it for via filesize function.

1
  • 3
    You need to use preg_replace_callback() + \w -> [\w./] Commented Dec 20, 2015 at 9:02

1 Answer 1

1

\w is only [A-Za-z0-9_] so you need to handle other characters, spaces etc. Either add all the types you need or maybe match everything up to ' %>'.

You can use preg_replace and then get the file size afterwards or use preg_replace_callback.

A couple of examples:

$oldStr = "<% size_../files/file with spaces.rar %>";

$size1 = preg_replace_callback("/<% size_([\w\.\/\s]+) %>/", 
    function ($matches) {
        return filesize($matches[1]);
    }, 
    $oldStr);


$newStr = preg_replace("/<% size_(.+) %>/", "$1", $oldStr);
if (is_file($newStr)) {
    $size2 = filesize($newStr);
} else {
    //not a file
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.