【问题标题】:Find element with class and add one more in php string查找具有类的元素并在 php 字符串中再添加一个
【发布时间】:2023-03-26 06:42:02
【问题描述】:

我正在尝试为 wordpress 中的音频短代码制作自己的过滤器。我想找到一个具有类的元素并再添加一个。我有带有 html 代码的 string 并且 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') 不固定。

【问题讨论】:

  • 您想将test-class 添加到每个mejs-container 元素中吗?
  • 是的,这就是我想要的
  • 为什么 str_replace 不起作用?
  • 我不知道...

标签: php wordpress class audio add


【解决方案1】:

您可以为此目的使用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");
}

【讨论】:

  • 我还是不知道该怎么做:(
  • 我在每一行都添加了注释来解释发生了什么以及 $dom 是如何设置的。你也可以让它使用$file = "test.html"; $dom = new DOMDocument(); $dom-&gt;loadHTMLFile($file);而不是上面的第一行从文件中加载HTML。如果你不知道如何在 wordpress 中弄乱 php 的东西,你也可以使用 javascript 来操作你的标签。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多