【问题标题】:php replace id element content in string [duplicate]php替换字符串中的id元素内容[重复]
【发布时间】:2020-04-27 18:23:49
【问题描述】:

有点卡住了,是否可以使用 PHP 来更新/更改 html 元素的内容。 因此,根据 id 名称仅替换下面字符串中的“Hello World”。

$html = '<h1 id="item" class="abc" data="efg">Hello World</h1>';

也许使用 preg_replace,只是想将所有其他内容保留在那里,例如。类、数据等

$html = preg_replace('<h1 id="item">????</h1>', 'New Content', $html);

谢谢

【问题讨论】:

标签: php


【解决方案1】:
May be below code will help 

$html = '<h1 id="item" class="abc" data="efg">Hello World</h1>';
$elementId = "item";
$newString = "Replace World";

$dom = new DOMDocument();
$dom->loadHTML($html);
$belement = $dom->getElementById("$elementId");
$oldString = $belement->nodeValue;


$newHTML = str_replace("$oldString","$newString","$html");
echo $newHTML;


Note: Please change $elementId and $newString with original values

【讨论】:

  • 谢谢大家 - 不胜感激!答案正是我所追求的。
猜你喜欢
  • 1970-01-01
  • 2012-02-27
  • 2023-03-15
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 2011-10-10
  • 2021-12-05
  • 1970-01-01
相关资源
最近更新 更多