This is a working implementation using preg_match:
$input = "<img src=\"http://www.example.com/img/img.png\" alt=\"A Title\">";
$re = '~(<img\s*src=".*\/).*(\.[^"]*)("\s*alt="([^"]+).*)~';
preg_match($re, $input, $m);
$filtered_string = $m[1] . str_replace(" ","_",strtolower($m[4])) . $m[2] . $m[3];
Output:
<img src="http://www.example.com/img/a_title.png" alt="A Title">
Interactive implementation here .
UPDATE : preg_replace_callback:
$filtered_string = preg_replace_callback(
'~(<img.*src=".*\/).*(\.[^"]*)(".*alt="([^"]+).*)~',
function($m) {
return $m[1] . str_replace(" ","_",strtolower($m[4])) . $m[2] . $m[3];
},
$str
);
- .