Search code examples
phpdocxopentbstinybutstrong

Change Text Colour of Part of a string in OpenTBS


I'm building a large word document, and need to change the text colour of 'part' of a string, only.

I've found similar questions in a few places here, here and here, but where my problem seems to differ, is that I only wish to colour part of a string, as opposed to a whole paragraph, or an entire OpenTBS field, as in these examples.

I first tried wrapping the individual chunk of string in docx XML tags, but found php converted then to entities (&gt; etc) which clearly was no use. Currently, I've moved on to wrapping the part of the text in XML tags through a template script, which gives me a malformed XML output, I presume because I have content between the </w:r> from one substring, and the <w:r> of the next substring.

Any advice on how to do this properly? Below is the current code and output.

//Function called onmerge. I wrap the portion of string I want to change the text 
//colour of with [UNTRANSLATED] and [ENDUNTRANSLATED] manually earlier, and attempt 
//to swap them for tags at this point.
function lb($FieldName, &$CurrVal) { 
    $CurrVal= str_replace('[UNTRANSLATED]', '<w:r><w:rPr><w:color w:val="FF0000"/></w:rPr><w:t>', $CurrVal); 
    $CurrVal= str_replace('[ENDUNTRANSLATED]', '</w:t></w:r>', $CurrVal); 
}

And the output...

<w:t> 
    <w:r> 
        <w:rPr> 
            <w:color w:val="FF0000" /> 
        </w:rPr> 
        <w:t>Slaked Lime</w:t> 
    </w:r>,
    <w:r>
         <w:rPr>
             <w:color w:val="FF0000" />
         </w:rPr>
         <w:t>Air slaked Lime</w:t>
    </w:r>,
[code continues in same style...]

Word flags the error at the point where my second block, and second <w:r> tag are. Unfortunately the error is beautifully non-descript.



Solution

  • The issue with the above code was that OpenTBS inputs strings into a pair of <w:r><w:t> tags, which need to be closed, before you insert your own. (As Sarah Kemp said in comments, <w:t> doesn't appear to be nestable.

    The below is an updated, working version. xml:space="preserve" also needed to be added to preserve spacing.

    //Function called onmerge. I wrap the portion of string I want to change the text 
    //colour of with [UNTRANSLATED] and [ENDUNTRANSLATED] manually earlier, and attempt 
    //to swap them for tags at this point.
    function lb($FieldName, &$CurrVal) {
      $CurrVal= str_replace('[UNTRANSLATED]', '</w:t></w:r><w:r><w:rPr><w:color w:val="FF0000"/></w:rPr><w:t xml:space="preserve">', $CurrVal);
      $CurrVal= str_replace('[ENDUNTRANSLATED]', '</w:t></w:r><w:r><w:t xml:space="preserve">', $CurrVal);
    }