Reputation: 5023
I am using this to split my title by space and make the first word a span for additional color styling,
$title = 'My new title';
$title = explode(' ', $title);
$title[0] = '<span>'.$title[0].'</span>';
$title= join(' ', $title);
As you can see I catch only first one in this case. What would be the fastest/best/correct way to wrap all title words in span ?
Upvotes: 0
Views: 331
Reputation: 2552
Preg replace
$title = "My new title";
echo preg_replace('/(\w+)/i', '<span>$1</span>', $title);
Upvotes: 0
Reputation: 149000
There's nothing wrong with the other answers, but here's an alternative solution using regular expressions:
$title = preg_replace('/\S+/', '<span>\0</span>', $title);
Upvotes: 0
Reputation: 207891
<?php
function span($n){
return('<span>'.$n.'</span>');
}
$title = 'My new title';
$title = explode(' ', $title);
$title = join(' ', array_map("span", $title));
print_r($title);
?>
Upvotes: 1
Reputation: 977
Use array_walk
$title = 'My new title';
$title = explode(' ', $title);
$title = array_walk($title, function(&$word) { return '<span>'.$word.'</span>'; })
$title= implode(' ', $title);
Upvotes: 1
Reputation: 167172
Do this way. Simple and Easy.
str_replace(" ", "</span><span>", $title);
$title = "<span>$title</span>";
Upvotes: 1
Reputation: 197
$title = 'My new title';
$title = explode(' ', $title);
foreach($title as $v)
{
echo $ti = '<span>'.$v.'</span>';
}
Upvotes: 1
Reputation: 3813
You could use a foreach
loop to do that:
$title = 'My new title';
$title = explode(' ', $title);
foreach ($title as $k => $v){
$title[$k] = '<span>'.$v.'</span>';
}
$title= join(' ', $title);
echo $title;
Upvotes: 1