繁体   English   中英

简单的PHP正则表达式与preg_replace

[英]simple php regex with preg_replace

我有这个字符串:

$string = '<div class="displayEmbededImage" sourcefile="http://site.com/images/myImage.jpg" style="width:200px;"><p>Some text goes here</p></div>';

我需要一个正则表达式,它将选择源文件的内容并像这样返回它:

$parern = '/<div(.*)sourcefile="([^"]+)"(.*)>(.*)<\/div>/s';
preg_replace($pattern, '<img src="$1">', $string);

到目前为止,我就是这样,但是还没有完全正确

HTML中使用正则表达式。 甚至不要尝试。 改用DOM:

$d = new DOMdocument();
$d->loadHTML('... your html here ...');
$xp = new DOMXpath($d);
$res = $xp->query('//div[@class="displayEmbededImage"]');
$source = $res->item(0)->getAttribute('sourcefile');

您的变量名中有一个错字,并且没有使用正确的占位符:

echo preg_replace($parern, '<img src="$2">', $string);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM