Quantcast
Channel: PHPWord
Viewing all articles
Browse latest Browse all 450

Commented Issue: Advanced string replace in setValue [49]

$
0
0
When started using Phpword it saved me a lot of time as i needed to replace a template in docx using php. I had a minor issue when started using the setValue method. I found that using Word, the program creates some tags that the str_replace couldn't detect.

I cracked a little bit the function, using some regular expressions in order to:
1. Find the regular expressions commencing with '${' and ending with '}' (in my case i dropped the $ sign cause i needed to use the $ sign in my word file)
2. With only that string, find and eliminate all the opening tags
3. find and eliminate the closing tags in that string
4. replace the old string (with garbage code) with the cleaned string
5. output the _documentXML

this is the piece of code I implemented if anyone is interested

Btw, great job with this tool it saved me a lot of time!

public function setValue($search, $replace) {
$pattern = '|\{([^\}]+)\}|U'; //if you need the $, use: '|\$\{([^\}]+)\}|U''
preg_match_all($pattern, $this->_documentXML, $matches);
$openedTagPattern= '/<[^>]+>/';
$closedTagPattern= '/<\/[^>]+>/';
foreach ($matches[0] as $value) {
$modificado = preg_replace($openedTagPattern, '', $value);
$modificado = preg_replace($closedTagPattern, '', $modificado);
$this->_documentXML = str_replace($value, $modificado, $this->_documentXML);
}

if(substr($search, 0, 1) !== '{' && substr($search, -1) !== '}') { //change to: substr($search, 0, 2) !== '${' if you need the $ character
$search = '{'.$search.'}'; //change to '${'.$search.'}' if $ needed
}

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

$this->_documentXML = str_replace($search, $replace, $this->_documentXML);
}
Comments: Thank you for this, it's saved me loads of hassle. The original SetValue function seemed to be very random in the way it worked in my documents - I now understand it was tags in Word that were confusing it. All you need to do is replace the existing function in Template.php (line 83) with this new one.

Viewing all articles
Browse latest Browse all 450

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>