Skip to content
Advertisement

Get attribute value and replace tag PHP

Consider the following HTML…

<p>Hello <var data-mach="reg_name">Registrant Name</var>, your email is <var data-mach="reg_email">Registrant Email</var></p>

And this array…

$data = [
  'reg_name' => 'Elon',
  'reg_mail' => 'elon@spacex.com'
];

How would I replace the var tags where I am able to use the data-mach attribute as the key for replacing the data?

The end result would be…

Hello Elon, your email is elon@spacex.com

I know I can do…

$str = '<p>Hello <var data-mach="reg_name">Registrant Name</var>, your email is <var data-mach="reg_email">Registrant Email</var></p>';

$result = preg_replace('/<var.*?var>/', 'Replaced', $str);

But how do I make the “replaced” value use the “data-mach” attribute?

Advertisement

Answer

Regex is not optimized, but you could try with https://www.php.net/manual/ru/function.preg-replace-callback.php

$str = '<p>Hello <var data-mach="reg_name">Registrant Name</var>, your email is <var data-mach="reg_email">Registrant Email</var></p>';

// $result = preg_replace('/<var.*?var>/', 'Replaced', $str);

$data = [
  'reg_name' => 'Elon',
  'reg_email' => 'elon@spacex.com'
];

$result = preg_replace_callback('/<var.*?"(.*?)".*?var>/', function ($matches) use ($data) {
            return $data[$matches[1]];
        }, $str);

var_dump($result);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement