I have a quick question about a preg_replace problem I have. I am just a newbie in RegEx.
What I would like to achieve is the following:
- I have a DIV tag
<div data-info="sourcefile.ext" class="elm swf">sourcefile</div> - I would like to extract the (data-info) value and the (class) value
- There might be optional tags but I don’t need te value of these attributes
- This replacement should work multiple times in one string
I have:
$input = '<div data-info="sourcefile.ext" class="elm swf">sourcefile</div>';
$input = preg_replace('/(<div\s(class="(.*?)")\s(data-info="(.*?)")\b[^>]*>)(.*?)<\/div>/i', "$1 class:$2 data-info:$3", $input);
I want to use the values as: <object src="(data-info)" type="(class)">
Is this possible? And can somebody show/explain me how this works?
Thank you very much.
Your regex fails because it lists the attributes in the wrong order. The match pattern does not accomodate for such things (which would be an actual reason to prefer using a DOM parser for such purposes.)
The
\bescape is misplaced. And you can wrap the two attributes into(?: .. | .. )+to allow for a little ambiguity:The $1 $2 $3 numbering was off, and maybe you want to use named capture groups here anyway.