Reputation:
I have the value like admin,bli
I have used this code to make the first letter capital
<?php ucfirst('admin,bli'); ?>
And my result is Admin,bli
My expected output is
Admin,Bli
How can I achieve this without using explode function and a for loop?
Upvotes: 1
Views: 2086
Reputation: 158020
You can use preg_replace_callback()
:
echo preg_replace_callback("/[^,]*/", function($m) {
return ucfirst($m[0]);
}, $str);
The pattern searches for a lower cased letter after a word boundary and replaces it by it's uppercased version.
An alternative would be to use array_reduce()
:
echo array_reduce(explode(',', $str), function($a, $b) {
return $a ? $a . ',' . ucfirst($b) : ucfirst($b);
});
Upvotes: 1
Reputation: 4980
<?php
echo join(',', array_map('ucfirst', explode(',', 'bill,jim')));
?>
Explode by comma, map ucfirst
every item using array_map
and implode it back by join
or implode
.
I know you'd like to avoid explode, but its probably quicker than preg_replace_callback
anyway.
Upvotes: 5