Search code examples
phpms-worddocboldphpword

PHPWord bold certain words on a line


I was wondering if there was a way to bold certain words on a line. For example if I wanted every third word on a line bold, how would I do it. I am currently using addText but that requires the whole line to be bold or not bold. Any responses would be greatly appreciated.


Solution

  • You will need to use createTextRun() method. I have tried with Text.php file from Examples folder, and here is code relevant for your problem:

    $textrun = $section->createTextRun();
    $sentence='I am sentence, and every third word will be bold. This is bold.';
    $word_arr=explode(' ', $sentence);
    
    $styleFont = array('bold'=>true, 'size'=>16, 'name'=>'Calibri');
    $styleFont2 = array('bold'=>false, 'size'=>16, 'name'=>'Calibri');
    
    $c = 0;
    for($i = 0; $i < count($word_arr); $i++) 
    {
        $c++;
        if($c % 3 == 0) 
        {
            $textrun->addText($word_arr[$i].' ', $styleFont);
        }
        else 
        {
            $textrun->addText($word_arr[$i].' ', $styleFont2);
        }
    }
    

    You could tweak it to get what you want, but, basically, by using of mentioned method, it is possible to get different styles in same line.