Forum


Replies: 4   Views: 1146
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

at DocxUtilities.inc

Usage: 

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

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

and it ouptputs: 

[0].-{{{contract_number}}}
[1].-{{{colaterals}}}
[2].-{{{customer_name}}}

 

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();
        $matches=array();

        // 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
        $docxFile->open($document);

        $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);
                $out=array();
                preg_match_all($regExp, $fileContent, $out);
                if(sizeof($out[0]) > 1)
                array_push($matches, $out[0]);
            }
        }
        $docxFile->close();
        $final=array();
        foreach($matches as $idx => $m)
        if(sizeof($m)>0)
        {
            foreach($m as $k => $v)
            $final[]=$v;
        }
        else
        $final[]=$m;
        return $final;
    }