PHPOffice / PHPWord

A pure PHP library for reading and writing word processing documents

Home Page:https://phpoffice.github.io/PHPWord/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Extension for PHPWord/src/PhpWord/IOFactory.php::extractVariables

neweldude opened this issue · comments

Is your feature request related to a problem? Please describe.

The function doesn´t get the placeholders from texts in tables.

Describe the solution you'd like

see below ;-)

Additional context

public static function extractVariables(string $filename, string $readerName = 'Word2007'): array
{
    $reader = IOFactory::createReader($readerName);
    $document = $reader->load($filename);
    $extractedVariables = [];
    foreach ($document->getSections() as $section) 
    {
        $concatenatedText = '';
        foreach ($section->getElements() as $element) 
        {
            if ($element instanceof TextRun) 
            {
                foreach ($element->getElements() as $textElement) 
                {
                    if ($textElement instanceof Text) 
                    {
                        $text = $textElement->getText();
                        $concatenatedText .= $text;
                    }
                }
            }
            
            else if ($element instanceof Table) 
            {
                foreach ($element->getRows() as $tableRows) 
                {
                    if ( $tableRows instanceof Row )
                    {
                        foreach ( $tableRows->getCells() as $tableCells )
                        {
                            if ( $tableCells instanceof Cell )
                            {
                                foreach ($tableCells->getElements() as $textrunElement) 
                                {
                                    if ($textrunElement instanceof TextRun)
                                    {
                                        foreach ($textrunElement->getElements() as $textElement)
                                        {
                                            if ($textElement instanceof Text)
                                            {
                                                $text = $textElement->getText();
                                                $concatenatedText .= $text;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        preg_match_all('/\$\{([^}]+)\}/', $concatenatedText, $matches);
        if (!empty($matches[1])) {
            foreach ($matches[1] as $match) {
                $trimmedMatch = trim($match);
                $extractedVariables[] = $trimmedMatch;
            }
        }
    }
    
    return $extractedVariables;
}