Not about optimization but more easier:
$txt = 'I just got finished coding this recursive function (my first one). It takes in $data, either an array or string, and an array of $terms to match against. It then matches, gets the entire word (not just cut off) and then adds an HTML span around it.';
$r = preg_replace('/(array|word|span)/', '<b>${1}</b>', $txt);
echo'<pre>',print_r($r),'</pre>';
Output is:
I just got finished coding this recursive function (my first one).
It takes in $data,either an <b>array</b> or string, and an <b>array</b> of $terms
to match against.
It then matches, gets the entire <b>word</b> (not just cut off)
and then adds an HTML <b>span</b> around it