Replies: 4   Views: 2963
Search with regular expression...
Topic closed:
Please note this is an old forum thread. Information in this post may be out-to-date and/or erroneous.
Every phpdocx version includes new features and improvements. Previously unsupported features may have been added to newer releases, or past issues may have been corrected.
We encourage you to download the current phpdocx version and check the Documentation available.

Posted by criptos  · 19-05-2017 - 15:28



for a pattern of {{{variable_name}}} inside document:

$matches=$newDocx->rawRegExpSearch('file_test.docx', '|{{{([a-zA-Z0-9_]+)}}}|');

and it ouptputs: 



Then I create a html form to fill in the values and generate a new document.


     * Search and replace text in any XML file of the document. Raw replacement, use carefully
     * @access public
     * @param string $document path to the document
     * @param string $regExp regular expression to match the regex
     * @return array of the value matches
    public function rawRegExpSearch($document, $regExp)
        $docxFile = new ZipArchive();
//         $finalDocument="finalDocumentRawRegExp".uniqid();

        // make a copy of the the document into its final destination to don't overwrite it
//         copy($document, $finalDocument);
        // extract (some) of the relevant files of the copy of the first document for manipulation

        $docxNumFiles = $docxFile->numFiles;
        // iterate the ZIP content and replace strings in the XML files
        for ($i = 0; $i < $docxNumFiles; $i++) {
            $fileName = $docxFile->getNameIndex($i);
            $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);

            if ($fileExtension == 'xml' || $fileExtension == 'rels') {
                // replace the string and save it in the ZIP file
                $fileContent = $docxFile->getFromName($fileName);
                preg_match_all($regExp, $fileContent, $out);
                if(sizeof($out[0]) > 1)
                array_push($matches, $out[0]);
        foreach($matches as $idx => $m)
            foreach($m as $k => $v)
        return $final;