PHP preg_replace guids over multiple lines



Hi there regex wizards!,

I have a document with multiple guids spread over multiple lines. I need to replace these guids with content from a file who’s name is the found guid. I’ve tried this:

preg_replace('/^[a-fd]{8}(-[a-fd]{4}){4}[a-fd]{8}$/i', file_get_contents("${1}.php"), $lines);

but it fails to find guids (and thus, also complains about ${1} not being found).

here is the multi-line string:

"
// Code in page

 //Run requested command: 
37906e3a-62f3-4d83-a8e0-9ad64a6a5228
de2dd82d-df13-4a8f-a760-cbc6e3db29d0

// bindings from HTML
af6236de-cf5d-447b-a9d5-28549aebd0fa
"

What I am doing wrong?

Thanks, Avi

Answer

You can use

preg_replace_callback(
  '/^(?:s?[a-fd]){8}s?(?:-(?:s?[a-fd]){4}){4}(?:s?[a-fd]){8}$/mi', 
  function($m) { 
    return file_get_contents(preg_replace("~s+~", "", $m[0]) . ".php"); 
  },
  $lines
);

See the regex demo.

The s? inside the pattern allows matching an optional whitespace anywhere in between each char of a match. Also, with regard to the regex pattern, you need to use m flag to make ^ and $ match line boundaries (start/end of the line, not just start/end of the whole string).

You can’t pass ${1} into a function within preg_replace replacement argument, you need a preg_replace_callback so that the match could be evaluated before passing it to a function.



Source: stackoverflow