Ame
Ame

Reputation: 163

PHP: Replace DOMElement with DOMText node

I want to create some customised tags for translating, for instance

<trad>SOMETHING</trad>

I've also got a file with some $GLOBALS variable, like:

$GLOBALS['SOMETHING'] = 'Some text';

$GLOBALS['SOMETHINGELSE'] = 'Some other text';

So I've been able to show my translation in this way:

$string = "<trad>SOMETHING</trad>";

$string = preg_replace('/<trad[^>]*?>([\\s\\S]*?)<\/trad>/','\\1', $string);
echo $GLOBALS[$string];

This works perfectly, but when I've got something more complex like the following code, or when I have more occurences of this tag, I'm not able to let it work:

$string = "Lorem ipsum <trad>SOMETHING</trad> <h1>Hello</h1> <trad>SOMETHINGELSE</trad>";

I ideally want to create a new variale $string, replacing the values that I found into my tags and being able to show it with a simple echo.

So I want an output like this with:

echo $string; //output: Lorem ipsum Some text <h1>Hello</h1> Some other text

Can you guys help me?

Upvotes: 1

Views: 150

Answers (1)

Sahil Gulati
Sahil Gulati

Reputation: 15141

Regex is not a valid approach for treating HTMLstring. Here we are using DOMDocument instead of Regex to achieve desired output. The last step of strip_tags has been done to achieve desired output, there will no need in case a valid HTML string is supplied to loadHTML, in that case saveHTML($node) will do the job.

Try this code snippet here

<?php
ini_set('display_errors', 1);

libxml_use_internal_errors(true);

$array["SOMETHING"]="some text";
$array["SOMETHINGELSE"]="some text other";

$string = "Lorem ipsum <trad>SOMETHING</trad> <h1>Hello</h1> <trad>SOMETHINGELSE</trad>";

$domDocument = new DOMDocument();
$domDocument->loadHTML($string,LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);

$results=$domDocument->getElementsByTagName("trad");
do
{
    foreach($results as $result)
    {
        $result->parentNode->replaceChild($domDocument->createTextNode($array[trim($result->nodeValue)]),$result);
    }
}
while($results->length>0);

echo strip_tags($domDocument->saveHTML(),"<h1>");

Upvotes: 2

Related Questions