Search code examples
regexstringescapingphpwordphpoffice

Escape '&' when filling in a docx document using PHPWord


I am building a web application which has to fill in a docx document. I am using the TemplateProcessor provided by PHPWord which takes a specific hook presenting on the document and replaces it with a given string. The problem that I have is when in the string an "&" is presenting - the document gets corrupted because of missing ';'.

The functions which I use to clear up the string are

$string = trim(html_entity_decode($string));
$string = strip_tags($string);
$string = trim(preg_replace('/\s+/', ' ', $string));

Does anyone has an idea how I can escape the ampersant symbol so the file will not get corrupted?


Solution

  • Certainly: see this HTML Entity chart:

    $str = preg_replace( '/&/', '&', $str );
    

    In your case however, it's better to add this line using htmlspecialchars:

    $str = htmlspecialchars( $str );