$s =<<< TXT TXT; echo preg_replace_callback('//i', 'foo', $s); function foo($r) { preg_match_all('/(\w+)="(.+?)"/', $r[0], $t); $t = array_combine($t[1], $t[2]); ksort($t); $s = ''; foreach($t as $k=>$v) $s .= " $k='$v'"; return ""; }