简体   繁体   中英

How to translate strings using xpath?

I have this piece of code:

$xpath = new DOMXPath($dom);
foreach ($xpath->query("//text()") as $q) {
    foreach(preg_split("/(\r?\n)/", $q->nodeValue) as $line) {
        $str = trim($line);
        $translation = search_in_db_for_translation($str);
        if (!empty($translation) {
            replace string previously found by $translation
        }
    }
}

The script searches in an XML document for each string and if there is an available translation in the database (pairs {"input language string", "input language string"}) it must replace the string in the DOM document (after this translation there are more DOM manipulations). The problem is I'm unable to find a function to do this.

EDIT : In order to be clear, what I need is a way to modify the current line and only the current line ($line var or $q->nodeValue). Please see JWiley answer and my comment.

您可以在XPath中使用translate()函数:

translate(text(), "oldText", "replacementText")

The answer is as easy as:

$xpath = new DOMXPath($dom);
foreach ($xpath->query("//text()") as $q) {
    foreach(preg_split("/(\r?\n)/", $q->nodeValue) as $line) {
        $str = trim($line);
        $translation = search_in_db_for_translation($str);
        if (!empty($translation) {
            $q->nodeValue = $translation;
        }
    }
}

It will replace the text and after this I just have to do a $dom->saveHTMLFile($out) in order to save the HTML file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM