Вы можете, вероятно, добиться того, что вам нужно с помощью preg_replace_callback
, а затем перекручивание через атрибуты снимка в функции обратного вызова.
Так, например, с учетом этого теста строка:
$content= <<<HTML
<img alt="image-alt-2" src="image-path" style="width: 20px; height: 15px; border: 1px solid red;" title="image-title" data-image-src="another_src" />
<p>Some other tags. These shouldn\'t be changed<br />Etc.</p>
<img alt="image-alt-2" src="image-path-2" style="width: 35px; height: 30px;" title="another-image-title" data-image-src="somewhere_else" />
HTML;
Мы можем затем спичку изображения и вызвать нашу заместительную функцию:
$content= preg_replace_callback('/<img ((?:[-a-z]+="[^"]*"\s*)+)\/>/i', 'replaceImage', $content);
В моем примере я просто извлекая на data-image-src
атрибут и использовать его для создания ссылки, все остальное остается как есть:
function replaceImage($matches) {
// matches[0] will contain all the image attributes, need to split
// those out so we can loop through them
$submatches= array();
$donelink= false;
$count= preg_match_all('/\s*([-a-z]+)="([^"]*)"/i', $matches[1], $submatches, PREG_SET_ORDER);
$result= '<img ';
for($ndx=0;$ndx<sizeof($submatches);$ndx++) {
if ($submatches[$ndx][1]=='data-image-src') {
// Found the link attribute, prepend the link to the result
$result= "<a href=\"{$submatches[$ndx][2]}\">$result";
$donelink= true; // We've added a link, remember to add the closing </a>
}
// You can handle anything else you want to change on an attribute-by-attribute basis here
else {
// Something else, just pass it through
$result.= $submatches[$ndx][0];
}
}
return "$result/>".($donelink?'</a>':'');
}
Выполнение этого на образце дает:
<a href="another_src"><img alt="image-alt-2" src="image-path" style="width: 20px; height: 15px; border: 1px solid red;" title="image-title"/></a>
<p>Some other tags. These shouldn\'t be changed<br />Etc.</p>
<a href="somewhere_else"><img alt="image-alt-2" src="image-path-2" style="width: 35px; height: 30px;" title="another-image-title"/></a>
Надеюсь, что это поможет!