我从我的sql表中提取了一个字符串值,如下所示:
<p>Commodity Exchange on 5 April 2016 settled as following graph:</p>
<p><img alt=\"\" src=\"ckeditor/plugins/imageuploader/uploads/986dfdea.png\"
style=\"height:163px; width:650px\" /></p></p>
<p>end of string</p>
我希望在html标记内获取图像名称 986dfdea.png (因为字符串中有很多<p></p>
个标记,我想知道这个标记包含图像),并用符号替换整个标记内容,如'#image1'。
最终会变成这样:
<p>Commodity Exchange on 5 April 2016 settled as following graph:</p>
#image1
<p>end of string</p>
我正在为移动应用开发API,但是拥有PHP的宝贝技能,仍然无法通过参考这些参考来实现我的目标:
PHP/regex: How to get the string value of HTML tag?
How to extract img src, title and alt from html using php?
请帮忙。
答案 0 :(得分:3)
是的,您可以使用正则表达式,但您需要更少的代码,但我们Accounts.findUserByUsername(),所以这就是您所需要的:
</p></p>
),因此我们使用
tidy_repair_string
要清理它。DOMXpath()
查询p
标记内的img
标记"
,并使用getAttribute("src")
和basename
createTextNode
#imagename
replaceChild
将p
内部图片替换为上面创建的新createTextNode
。!DOCTYPE
html
,body
和new DOMDocument();
代码
醇>
<?php
$html = <<< EOF
<p>Commodity Exchange on 5 April 2016 settled as following graph:</p>
<p><img alt=\"\" src=\"ckeditor/plugins/imageuploader/uploads/986dfdea.png\"
style=\"height:163px; width:650px\" /></p></p>
<p>end of string</p>
EOF;
$html = tidy_repair_string($html,array(
'output-html' => true,
'wrap' => 80,
'show-body-only' => true,
'clean' => true,
'input-encoding' => 'utf8',
'output-encoding' => 'utf8',
));
$dom = new DOMDocument();
$dom->loadHtml($html);
$x = new DOMXpath($dom);
foreach($x->query('//p/img') as $pImg){
//get image name
$imgFileName = basename(str_replace('"', "", $pImg->getAttribute("src")));
$replace = $dom->createTextNode("#$imgFileName");
$pImg->parentNode->replaceChild($replace, $pImg);
# loadHTML causes a !DOCTYPE tag to be added, so remove it:
$dom->removeChild($dom->firstChild);
# it also wraps the code in <html><body></body></html>, so remove that:
$dom->replaceChild($dom->firstChild->firstChild, $dom->firstChild);
echo str_replace(array("<body>", "</body>"), "", $dom->saveHTML());
}
<强>输出:强>
<p>Commodity Exchange on 5 April 2016 settled as following graph:</p>
<p>#986dfdea.png</p>
<p>end of string</p>