我在数据库中有这样的条目:
<div>
<a href="path/img.jpg">
<img src="path/img.jpg"/>
</a>
Photograph: Name of Photographer
</div>
想要达到的目的是,围绕imagedescription制作一个p-Tag
为了获取文本,我有这样的正则表达式:
$regex_pattern = "/.jpg\"\/><\/a>(.*)<\/div>/";
$replace = ".jpg\"/></a><p class=\"img-caption\">$1</p></div>/";
$content = preg_replace($regex_pattern, $replace, $content);
但是在我的图像描述后我得到一个空的p-tag。我做错了什么
答案 0 :(得分:1)
您没有包含可能的空格或换行符,请将您的模式更改为:
$regex_pattern = "/.jpg\"\/>\s*<\/a>\s*(.*)\s*<\/div>/";
在此处查看:
http://sandbox.onlinephpfunctions.com/code/d74f8c65c3cef80fe88721269e2c97004e0b9a68
答案 1 :(得分:1)
我不能强调这一点,不要使用正则表达式进行HTML解析。相反,使用DOMDocument更容易,更安全。这只是实现目标的几种方法之一。我们的想法是解析HTML,找到最后一个文本节点,然后将其包装在^\+92[0-9]{10}$
标签中。
<p>
<强>输出:强>
$dom = new DOMDocument;
// Load the HTML without saving the wrapper info
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xp = new DOMXPath($dom);
$textNodes = $xp->query('//div/text()');
$lastTextNode = $textNodes->item($textNodes->length - 1);
$element = $dom->createElement('p');
$element->nodeValue = $lastTextNode->nodeValue;
$lastTextNode->parentNode->replaceChild($element, $lastTextNode);
echo $dom->saveHTML();
演示: IDEOne