我试图在wordpress中创建自己的音频短代码过滤器。我想找到一个带有类的元素并添加一个。我有字符串和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;">
我想添加&#39; 测试级&#39;用&#39; mejs-container &#39;来划分。我想补充一点,ID(&#39; mep_0&#39;)不固定。
答案 0 :(得分:3)
您可以使用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");
}