Question

Hi i need to wrap the last letter of a string in a span tag, how can i do this in php?

for instance:

$string = 'Get on the roller coaster';

Should be output:

'Get on the roller coaste<span>r</span>'
Was it helpful?

Solution

find

(.)$

replace with

<span>\1</span>

demo here : http://regex101.com/r/bY8kX0

like this in php:

<?php
$string = 'Get on the roller coaster';
echo preg_replace('/(.)$/', '<span>\1</span>', $string);

OTHER TIPS

Use this regex:

(.)$

And replace it with:

<span>\1</span>

. means a character and $ means the end and () is used to group the character so it can be used.

So the regex says: Match the last character.

I think this is a overkill and would have given a native php answer but, I don't know php :)

Thanks sshashank124 for the grouping tip!

I'll probably get bashed for inefficiency but here is an alternative :)

// your string :)
$string = 'Get on the roller coaster';

// count the chars of your string, not the bytes ;)
$stringLength = mb_strlen($string);

// a string's characters can be accessed in array form IF it is an actual string and not an INT or w/e
// echo $string[0] would produce the letter 'G'
// so we want the last character, right-o!
$wrapped = '<span>'.$string[($stringLength - 1)].'</span>';

// mb_substr() the old string and give it that <span>-wrapped char
$newString = mb_substr($string, 0, -1).$wrapped;

// and presto!
// $newString is now === Get on the roller coaste<span>r</span>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top