PHPWord bold certain words on a line

user2579723 picture user2579723 · Jul 13, 2013 · Viewed 7.8k times · Source

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.

Answer

sinisake picture sinisake · Jul 13, 2013

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.