Extract html attributes from string in PHP
arrays, dom, function, parsing, php
Solution
You can extract the values by using some string functions. It looks like this:
$test1 = '<li data-tpl-classname="class" data-tpl-title="innerHTML"></li>';
$test2 = '<div data-tpl-anything="something" data-tpl-title="this is a title" data-tpl-third="asdasd"></div>';
var_dump(extract_tpl($test1));
var_dump(extract_tpl($test2));
function extract_tpl($string,$prefix="data-tpl-") {
$start = 0;
$end = 0;
while(strpos($string,$prefix,$end))
{
$start = strpos($string,$prefix,$start)+strlen($prefix);
$end = strpos($string,'"',$start)-1;
$end2 = strpos($string,'"',$end+2);
$array[substr($string,$start,$end-$start)] = substr($string,$end+2,$end2-$end-2);
}
return $array;
}
Output:
array (size=2)
'classname' => string 'class' (length=5)
'title' => string 'innerHTML' (length=9)
array (size=3)
'anything' => string 'something' (length=9)
'title' => string 'this is a title' (length=15)
'third' => string 'asdasd' (length=6)
The numbers in the code ( -1, +2, ... ) is for skipping the symbols like " .
Problem
I have a variable that looks like this: ``` $var = '<li data-tpl-classname="class" data-tpl-title="innerHTML"></li>' ``` and I want to extract the data-tpl-attributes in a way so I end up with a resulting array that looks like this: ``` $array = ( 'classname' => 'class', 'title' => 'innerHTML' ) ``` The number of "data-tpl-" attributes varies, and it's not always an `<li>` element. Other than that, it always follows the same format: `data-tpl-attributename="attributePlacement"`. How can I retrieve those attributes and store them in an array, without using regex? I say without regex since everywhere I look it seems like parsing html using regex is an evil practice, or is it ok in this case?