我有一个包含文本和图像的富文本字段(称为描述)
我尝试隔离所有图像以修改src标签以在
之前和之后添加元素示例:<img src="path/to/myimage.jpg" />
应该变为<img src="timthumb.php1src=path/to/myimage.jpg&h=50" />
当我的领域只有一张图片时,我成功了,我用它:
$descriptionencodee = utf8_encode($description);
$parser = xml_parser_create();
xml_parse_into_struct($parser, $descriptionencodee, $values);
foreach ($values as $key => $val) {
if ($val['tag'] == 'IMG') {
$first_src = $val['attributes']['SRC'];
break;
}
$string = $description;
$replacement = '<img src="'timthumb.php?src='. $first_src .'&h=50" />';
// $replacement = '${1}<br/>';
$string = preg_replace("/(\<img\b[^>]*>)/", $remplacement, $string);
echo $string;
所以当有多个图像时它不起作用
答案 0 :(得分:1)
这在最近的项目中对我有用:
<?php
$content = $your_html_here;
preg_match_all( '/<img .* \/>/iU', $content, $results ); // Find all <img />
foreach ( $results[0] as $one_image ){ // Loop through results
// Replace <img /> with altered <img />
$content = str_replace( $one_image, str_replace( 'src="', 'src="timthumb.php?h=50&src=', $one_image ), $content );
}