tags:

views:

46

answers:

1

Whats the fastest possible way to do this?

I think the code below works, but I'm sure there's a faster way to achieve what I want:

$words = explode(" ", $string);
if(!empty($words[1]) $words[1] = '<span>'.$words[1].'</span>';
$string = implode(" ", $words);

What do you think?

+2  A: 

As zerkms and deceze point out in their comments, I'm sure your scripts will receive more effective optimizations elsewhere unless you're sure your performance bottleneck lies in the above snippet.

That said, if for example you don't want to muck around with arrays, try this, assuming each word is only separated by one space character:

$string = trim($string);

if (strpos($string, ' ') !== false) {
    $string = str_replace(' ', ' <span>', $string) . '</span>';
}
BoltClock