Reputation: 29
im trying to change html elements inside PHP.
first is to replace textarea with h1. Thing needs to be replaced looks something like this:
<textarea class="head" id="hd_x">Random headline</textarea>
Im trying to change to this:
<h1 class="head" id="hd_x">Random headline</h1>
Random headline can be- Dog like cats, Cats dont like dogs.
X in id can be number- hd_1, hd_2 and so on( but i think it is no needed to be touched, so it can be ignored ).
Second is need to replace textarea with p. Original looks something like this:
<textarea class="text" id="txt_x">Random text</textarea>
Im trying to change to this:
<p class="text" id="txt_x">Random text</h1>
Random text and X here works same as on first one
If you can figure out what im trying to do and it is possible and short then tt would be nice if you help me to do only the H1 part. I think i can figure <p>
(2nd) part out it.
I tryed to do it with str_replace but the problem is that then it is always replacing </textarea>
with </h1>
or with </p>
Thank you
My idea is is that i need 2 separate preg_replace. One of them recognizes this part:
<textarea class="head"
knows it needs to replace with :
<h1 class="head"
Thems skips over this part:
id="hd_x">Random headline
then it preg_replace recognizes again this one:
</textarea>
and replaces with:
</h1>
Trying to make it short. Finds by this(???? is part that should be ignored and left untouched):
<textarea class="head" ??????????????????</textarea>
and replaced with(????? is part that was untouched):
class="head" i think is needed cause preg_replace pattern figures out this way that it need to replace with h1 not with p.
Upvotes: 0
Views: 124
Reputation: 19492
You should not use RegEx to change HTML elements. The DOM recognizes the structure and xpath makes it easy to do what you want:
$html = <<<'HTML'
<html>
<body>
<textarea class="head" id="hd_x">Random headline</textarea>
<textarea class="text" id="hd_x">Random headline</textarea>
</body>
</html>
HTML;
$dom = new DOMDocument();
$dom->loadHtml($html);
$xpath = new DOMXpath($dom);
$names = array(
'head' => 'h1', 'text' => 'p'
);
$nodes = $xpath->evaluate('//textarea[@class="head" or @class="text"]');
foreach ($nodes as $node) {
// create the new node depending on the class attribute
$type = $node->getAttribute('class');
$newNode = $dom->createElement($names[$type]);
// fetch all attributes of the current node
$attributes = $xpath->evaluate('@*', $node);
// and append them to the new node
foreach ($attributes as $attribute) {
$newNode->appendChild($attribute);
}
// replace the current node with the new node
$node->parentNode->replaceChild($newNode, $node);
}
var_dump($dom->saveHtml());
Upvotes: 0