Change color of first and last letter of a word php

Lets say I have a variable like this

$word = 'basketball';

I want to be able to change the color of the first and last letter of the word, so my output would be

<span style="color:#0000FF>b</span>asketbal<span style="color:#0000FF>l</span>

Im sure strlen() will be needed in there but racking my brain how to come up with this
LVL 1
cbielichAsked:
Who is Participating?
 
Phil PhillipsConnect With a Mentor Director of DevOps & Quality AssuranceCommented:
You're on the right track with strlen().  Combined with substr_replace(), you can get the desired result:

$word = substr_replace($word, '<span style="color:#0000FF">' . $word[0] . '</span>', 0, 1);
$i = strlen($word) - 1;
$word = substr_replace($word, '<span style="color:#0000FF">' . $word[$i] . '</span>', $i, 1);
echo "$word\n";

Open in new window

0
 
BardobraveCommented:
$result = '<span style="color:#0000FF>' + substr($word,0,1) + '</span>' + substr($word, 1, strlen($word) - 2) + '<span style="color:#0000FF>' + substr($word, strlen($word) - 1, 1) + '</span>'

Basically build a string with:
The start of the span of the rist letter
+ a substring of $word from it's char 0 including one char (that's it's first letter)
+ the closing of the first span
+ a substring of $word from it's second char of it's length -2 chars (that's it's whole length except it's first and it's last letters)
+ the opening of the second span
+ a substring of $word from it's last char of 1 char (that's the last letter)
+ the closing of the second span

I'm sure you catch the glimpse.
0
 
Julian HansenCommented:
<!doctype html>
<html>
<head>
<style type="text/css">
.first {
	color: red;
}
.last {
	color: blue;
}
</style>
</head>
<body>
<?php
$word = 'basketball';
$newword = sprintf("<span class=\"first\">%s</span>%s<span class=\"last\">%s</span>", 
	substr($word,0,1), substr($word, 1, strlen($word)-2), substr($word, -1));
echo $newword;
?>
</body>
</html>

Open in new window

0
 
Ray PaseurCommented:
See http://www.laprbass.com/RAY_temp_cbielich.php

<?php // RAY_temp_cbielich.php
error_reporting(E_ALL);

// FUNCTION TO CHANGE COLORS OF FIRST AND LAST LETTERS OF A STRING
function change_colors($word, $a='', $z='')
{
    $arr = str_split($word);
    $num = count($arr) - 1;
    $arr[0]
    = '<span style="color:'
    . $a
    . ';">'
    . $arr[0]
    . '</span>'
    ;

    $arr[$num]
    = '<span style="color:'
    . $z
    . ';">'
    . $arr[$num]
    . '</span>'
    ;


    return implode(NULL, $arr);
}

// TEST THE FUNCTION
echo '<pre>';
echo PHP_EOL . change_colors('basketball');
echo PHP_EOL . change_colors('basketball', 'red', 'blue');
echo PHP_EOL . change_colors('golf', 'green', 'green');
echo PHP_EOL . change_colors('ping pong', 'gray');
echo PHP_EOL . change_colors('baseball', '#992200', '#0000cc');
echo PHP_EOL . change_colors('hockey', NULL, 'orange');

Open in new window

0
All Courses

From novice to tech pro — start learning today.