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: 

// bindings from HTML

What I am doing wrong?

Thanks, Avi


You can use

  function($m) { 
    return file_get_contents(preg_replace("~s+~", "", $m[0]) . ".php"); 

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