示例我有一个像这样的img标签…
<img alt="INLINE:143246;w=240;h=240" class="wysiwyg-inline-image" src="/sites/default/files/styles/inline_image_temp_240x240/public/2013/05/30/600x600_30.png?itok=7mP9F2QH" />
我想把它替换成…
<p><!-- INLINE:143220;w=240;h=240 --></p>
,然后根据img
alt属性保存到DB。
注意:图片的数量是动态的,因为用户可能会上传多个不同大小的图片。图片大小在图片alt上。
到目前为止,我有这个代码。
preg_match_all("/(<img[^>]+>)/i", $node->body[LANGUAGE_NONE][0]['value'], $matches);
foreach($matches as $match) {
// Replace all matched elements here.
}
如果您想替换它,那么使用preg_replace。假设您在$str变量中获得了字符串,那么下面将是使用preg_replace的方法。
$str = preg_replace('/<img.*?alt="(.+?)".*?>/', '<p><!-- $1 --></p>', $str);
$html = $node->body[LANGUAGE_NONE][0]['value']; // saving value in a variable to manipulate
preg_match_all("/(<img[^>]+>)/i", $html , $matches); // returns all image tags
foreach($matches as $match) {
$str = preg_replace('/<img.*alt="(.+?)".*?>/', '<p><!-- $1 --></p>', $html);
// get the alt tag text
$html = str_replace($mathch, $str, $html); replace in the original string
}
// save $html in database