Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using each match in preg_replace() in PHP

Tags:

string

regex

php

I've read through multiple tutorials on regex and it's associated functions but I am stumped on this one.

I have a really simple replace that looks for a specific delimiter and parses the name of a PHP variable. Here it is:

var_dump(preg_replace('/{{\$(.*?)}}/', ${$1}, $this->file));

I keep getting errors about php not liking the #1 in ${$1}. Fair enough, can't start a variable name with a number, I knew that...

So I tried:

var_dump(preg_replace('/{{\$(.*?)}}/', ${'$1'}, $this->file));

Same thing.

Yet if I try:

var_dump(preg_replace('/{{\$(.*?)}}/', '$1 yo', $this->file));

It works...

So, how do I get php to echo a variable named whatever $1 is.

For example:

$hola = yo;
$string = hello{{$hola}}hello{{$hola}};
var_dump(preg_replace('/{{\$(.*?)}}/', ${$1}, $string));

And the output would be:

helloyohelloyo

Spank you!

EDIT

I should also mention that I am aware that there is a standard recommendation on how to match php variables with regex, but i'd like to get it working with a regex that I fully understand first.

like image 776
Matthew Goulart Avatar asked Dec 02 '25 09:12

Matthew Goulart


1 Answers

Like so:

$hola = 'yo';
$string = 'hello{{$hola}}hello{{$hola}}';
$result = preg_replace_callback('/\{\{\$(.*?)\}\}/', function ($matches) use ($hola) {
    return ${$matches[1]};
}, $string);
var_dump($result);

preg_replace_callback calls a callback on every match.

In order to use the $hola variable inside the callback you need to explicitly make it available inside the function (use ($hola)).

All this said... I don't get it. What this code does is essentially what PHP already does out-of-the-box.

$hola = 'yo';
$string = "hello{$hola}hello{$hola}";
echo $string; // "helloyohelloyo"
like image 119
Sverri M. Olsen Avatar answered Dec 03 '25 23:12

Sverri M. Olsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!