Regular expression in XML string

Asked

Viewed 313 times

0

Hello, I’m using a PHP library to generate words with some parameters.

The library is Phpword, when I upload a file (DOCX) it opens the Document.xml file inside the DOCX archive.

Example:

<?php
$phpWord = new PHPWord('teste.docx');
$phpWord->setValue('oi', 'tudo bem');

The problem is that word XML should look like this:

<w:t>${oi}</w:t>

But it’s getting that way (in some cases):

${</w:t></w:r><w:bookmarkStart w:id="1" w:name="OLE_LINK1"/><w:r w:rsidRPr="00036D2C"><w:t>oi</w:t></w:r><w:bookmarkEnd w:id="1"/><w:r w:rsidRPr="00036D2C"><w:t>}</w:t>

Why does Phpword setValue replace the loaded string

/**
 * Set a Template value
 * 
 * @param mixed $search
 * @param mixed $replace
 */
public function setValue($search, $replace) {
    if(substr($search, 0, 2) !== '${' && substr($search, -1) !== '}') {
        $search = '${'.$search.'}';
    }

    if(!is_array($replace)) {
        $replace = utf8_encode($replace);
    }



    $this->_documentXML = str_replace($search, $replace, $this->_documentXML);
}

How could I fix this using regular expression? Thank you.

  • Can I share a functional example by calling this function? And what do you mean by "in some cases"?

  • Hello Peter in the question already has the example. Vlws

  • Sorry, I wasn’t clear enough. Which input instance you are using in this.docx test?

  • And why wouldn’t that be right? <w:t>oi</w:t> is contained in the second example. What is the difference in the final result with the extra Markup?

1 answer

0

This regex captures the nonspecial characters that are between the tags <w:t> and <\/w:t>

(<w:t>[a-zA-Z0-9]*<\/w:t>)

She would return <w:t>oi</w:t> then you could use a replace to put ${ and }.

  • It didn’t work... it didn’t replace

  • replace must be done through a method, outside the regex, use the return of regex and add these characters friend

Browser other questions tagged

You are not signed in. Login or sign up in order to post.