Benn
Benn

Reputation: 5023

How to replace space with span PHP?

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

Answers (7)

jPO
jPO

Reputation: 2552

Preg replace

$title = "My new title";
echo preg_replace('/(\w+)/i', '<span>$1</span>', $title);

Upvotes: 0

p.s.w.g
p.s.w.g

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

j08691
j08691

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

MueR
MueR

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

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Do this way. Simple and Easy.

str_replace(" ", "</span><span>", $title);
$title = "<span>$title</span>";

Upvotes: 1

Neeraj
Neeraj

Reputation: 197

$title = 'My new title';
$title = explode(' ', $title);
foreach($title  as $v)
{
  echo $ti = '<span>'.$v.'</span>';
}

Upvotes: 1

larsAnders
larsAnders

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

Related Questions