I am walking through some attributes in a shortcode in wordpress with code. I got all attributes in one string. Like this:
$var = 'type="text" title="super title" class="master-module"';
I want to convert it to:
$var = 'data-type="text" data-title="super title" data-class="master-module"';
I have tried to understand using preg replace but I terrible at regex.
Any help is appreciated.
You can use a regex like this:
(\w+=")
And this replace string:
data-$1
You can see the match and capturing groups in green and in the substitution section your resulting string after applying the replacement string.
The php code:
$re = "/(\\w+=\")/";
$str = "\$var = 'type=\"text\" title=\"super title\" class=\"master-module\"';
";
$subst = "data-\1";
$result = preg_replace($re, $subst, $str);
Update: If you have an attribute with dashes like heading-type="xxx xx"
then you can use this regex instead:
([\w-]+=")
You can explode, apply the wanted addition on every element that needs to be prefixed, and implode your string to get the expected result :
$var = 'type="text" title="super title" class="master-module"';
$var = explode (' ', $var);
array_walk ($var, function (&$a) {
if (strpos($a, '"') !== strlen($a) - 1)
$a = 'data-' . $a;
});
$var = implode (' ', $var);
// data-type="text" data-title="super title" data-class="master-module"
That way, you could also add an array to your array_walk call to include a list of values to modify or to exclude also.
Here is my final code and answer.
$re = '/([\w-]+=")/';
$str = $moduleAttribute;
$subst = 'data-$1';
$result = preg_replace($re, $subst, $str);
I just have one word. Thanks! Especially thank you @fede