[英]PHP str_ireplace does not remove content from DomDocument tags
我正在嘗試通過充當stripos
來檢查td
是否確實具有class
屬性並從td
中str_ireplace
具有class
屬性的所有內容,以替換此navigation-only
CSS 內容類( <td class="navigation-only"> ... </td>
) 帶有空雙引號,如下面的代碼所示:
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://website.ndd");
$getTableTags = $doc->getElementsByTagName("table");
$getTdTags = $doc->getElementsByTagName("td");
foreach ($getTableTags as $getTableTag) {
if (stripos($getTableTag->getAttribute('class'), "infotec") !== false) {
foreach ($getTdTags as $getTdTag) {
if (stripos($getTdTag->getAttribute('class'), "navigation-only") !== false) {
// var_dump($getTableTag);
// $completeInfoxbox = $doc->saveHTML($getTableTag);
$getInfoboxPatch1 = str_ireplace($getTdTag, "", $getTableTag);
echo $doc->saveHTML($getInfoboxPatch1);
}
}
}
}
我得到一個 100% 的空白頁面,但我做了一個: echo $doc->saveHTML($getInfoboxPatch1)
。
那么,如何更正我的代碼以刪除所有具有class
屬性的<td>
HTML 標記,其class
屬性的內容是navigation-only
: <td class=" navigation-only"> ... </td>
???
請幫幫我。
$getInfoboxPatch1 = str_ireplace($getTdTag, "", $getTableTag);
// throws error: str_ireplace(): Argument #1 ($search) must be of type array|string, DOMElement given
str_ireplace
將字符串或數組作為搜索和對象參數。 您正在傳遞PHP DOMElements
。
要更改 PHP DOMDocument 元素,您需要刪除現有元素,創建一個新元素,並將其附加到舊元素的父元素。
在這種情況下,您將刪除一個文本節點,創建一個新文本節點,並將新文本節點附加到 TD 標記:
if (stripos($getTdTag->getAttribute('class'), "navigation-only") !== false) {
// remove child nodes
while ( $getTdTag->hasChildNodes() ) {
$getTdTag->removeChild($getTdTag->firstChild);
}
// create empty text node
$emptyTextNode = $doc->createTextNode("");
// append to TD tag
$getTdTag->appendChild($emptyTextNode);
//show updated tag
echo $doc->saveHTML($getTdTag);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.