Doğru Cevap
-
function element_attributes($element_name, $xml) { if ($xml == false) { return false; } // Grab the string of attributes inside an element tag. $found = preg_match_all('#<'.$element_name. '\s+([^>]+(?:"|\'))\s?/?>#', $xml, $match); $allAttr = array(); if ($found > 0) { foreach($match[1] as &$searchTag) { $attribute_array = array(); $attribute_string = $searchTag; // Match attribute-name attribute-value pairs. $found = preg_match_all( '#([^\s=]+)\s*=\s*(\'[^<\']*\'|"[^<"]*")#', $attribute_string, $matches, PREG_SET_ORDER); if ($found != 0) { // Create an associative array that matches attribute // names to attribute values. foreach ($matches as $attribute) { $attribute_array[$attribute[1]] = substr($attribute[2], 1, -1); } $allAttr[] = $attribute_array; } } return $allAttr; } // Attributes either weren't found, or couldn't be extracted // by the regular expression. return false; } $str = '<input type="text" name="username" value="Kullanıcı Adınız" /><input type="password" name="pass" value="Şifreniz" /><input type="hidden" name="lan" value="tr" />'; $txt = element_attributes('input', $str); echo "<pre>"; print_r($txt);
çıktısı
/* Array ( [0] => Array ( [type] => text [name] => username [value] => Kullanıcı Adınız ) [1] => Array ( [type] => password [name] => pass [value] => Åifreniz ) [2] => Array ( [type] => hidden [name] => lan [value] => tr ) ) */
Cevaplar
-
regexp ile parsing yapmaya çalışmak pek tavsiye edilen bir yöntem değildir. sana tavsiyem bu tip parsing işlerini yapan bir lib kullanman. mesela "simple html dom" senin problemini çözer sanırım. (http://simplehtmldom.sourceforge.net)