查找带有 class 的元素并在 php 字符串中再添加一个
Find element with class and add one more in php string
我正在尝试为 wordpress 中的音频简码创建自己的过滤器。我想 找到一个带有 class 的元素并再添加一个 。我有 string 和 html 代码,但 str_replace 不起作用。
<div id="mep_0" class="mejs-container svg mejs-audio" tabindex="0" role="application" aria-label="Audio Player" style="width: 416px; height: 30px;">
我想用'mejs-container将'test-class'添加到div '.我想补充一点,id ('mep_0') 不固定。
您可以使用 Xpath 来达到这个目的。
这是一个简单的例子:
$dom = '<div id="mep_0" class="mejs-container svg mejs-audio" tabindex="1" role="application" aria-label="Audio Player" style="width: 416px; height: 30px;">
<div id="mep_1" class="mejs-container svg mejs-audio" tabindex="0" role="application" aria-label="Audio Player" style="width: 416px; height: 30px;">
<div id="mep_2" class="mejs-container svg mejs-audio" tabindex="0" role="application" aria-label="Audio Player" style="width: 416px; height: 30px;">';
$xpath = new DomXPath($dom); // read xml/html into dom to manipulate or search stuff
$elements = $xpath->query('//div[contains(@class,"mejs-container")]'); // search elements that contain "mejs-container" class
// loop through each found element
foreach($elements as $element) {
// get the current class attributes content
// which would give you "mejs-container svg mejs-audio"
$currentClass = $element->getAttribute('class');
// append "test-class" to the current value and set it in the dom (mind the space between classes)
$element->setAttribute($currentClass . " test-class");
}
我正在尝试为 wordpress 中的音频简码创建自己的过滤器。我想 找到一个带有 class 的元素并再添加一个 。我有 string 和 html 代码,但 str_replace 不起作用。
<div id="mep_0" class="mejs-container svg mejs-audio" tabindex="0" role="application" aria-label="Audio Player" style="width: 416px; height: 30px;">
我想用'mejs-container将'test-class'添加到div '.我想补充一点,id ('mep_0') 不固定。
您可以使用 Xpath 来达到这个目的。
这是一个简单的例子:
$dom = '<div id="mep_0" class="mejs-container svg mejs-audio" tabindex="1" role="application" aria-label="Audio Player" style="width: 416px; height: 30px;">
<div id="mep_1" class="mejs-container svg mejs-audio" tabindex="0" role="application" aria-label="Audio Player" style="width: 416px; height: 30px;">
<div id="mep_2" class="mejs-container svg mejs-audio" tabindex="0" role="application" aria-label="Audio Player" style="width: 416px; height: 30px;">';
$xpath = new DomXPath($dom); // read xml/html into dom to manipulate or search stuff
$elements = $xpath->query('//div[contains(@class,"mejs-container")]'); // search elements that contain "mejs-container" class
// loop through each found element
foreach($elements as $element) {
// get the current class attributes content
// which would give you "mejs-container svg mejs-audio"
$currentClass = $element->getAttribute('class');
// append "test-class" to the current value and set it in the dom (mind the space between classes)
$element->setAttribute($currentClass . " test-class");
}