指定されたhtmlのルートタグにいくつかの属性を追加する関数を作りたいです。
私はこれをやっています:
$dom = new \DOMDocument();
$dom->loadHTML($content);
$root = $dom->documentElement;
$root->setAttribute("data-custom","true");
そして、$content='<h1 class="no-margin">Lorem</h1>'
戻り値:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html data-custom="true"><body><h1 class="no-margin">Do more tomorrow. For less.</h1></body></html>
だけである必要がありますが:
<h1 data-custom="true" class="no-margin">Lorem</h1>
DOMDocument で doctype、html、body タグを作成せず、指定された html だけを操作する方法と、指定された html のルート ノードを選択する方法
Ps。HTMLの管理に正規表現を使用することはありません。