因此,我需要将"inlineAssetLink"类注入到属于段落一部分的锚标记中,但将"blockAssetLink"类注入到位于空段落内的锚标记中.
不确定这是否可以使用x路径,但内容来自cms中的所见即所得编辑器,我想在服务器端而不是使用JavaScript进行此操作.
已经使用DOMASYS来操纵内容的其他部分,因此最好对此做同样的事情.
因此,我需要将"inlineAssetLink"类注入到属于段落一部分的锚标记中,但将"blockAssetLink"类注入到位于空段落内的锚标记中.
不确定这是否可以使用x路径,但内容来自cms中的所见即所得编辑器,我想在服务器端而不是使用JavaScript进行此操作.
已经使用DOMASYS来操纵内容的其他部分,因此最好对此做同样的事情.
以下代码将其加载到DOMDocument
中,并通过判断每个锚点的父级的子级计数将这些类应用到所有锚点.
function addClassesToAnchors($html)
{
$dom = new DOMDocument();
$dom->loadHTML(
"<div class='my-wrapper'>$html</div>",
LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD
);
// get all anchors
$anchors = $dom->getElementsByTagName('a');
foreach ($anchors as $anchor) {
$parentNode = $anchor->parentNode;
if ($parentNode->nodeName == 'p') {
$childNodes = $parentNode->childNodes;
// count children, expect 1 for empty p
$count = 0;
foreach ($childNodes as $childNode) {
$count++;
}
if ($count == 1) {
$anchor->setAttribute('class', 'blockAssetLink');
}
if ($count > 1) {
$anchor->setAttribute('class', 'inlineAssetLink');
}
}
}
// Get the content as HTML without the <div> wrapper
$divElement = $dom->documentElement;
$result = '';
foreach ($divElement->childNodes as $node) {
$result .= $dom->saveHTML($node);
}
return $result;
}
$html = "<p><a></a></p> <p>but not</p> <p>sometext<a>link</a>or some text</p>";
echo addClassesToAnchors($html);