ucfirst after comma separated value

2k Views Asked by At

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?

2

There are 2 best solutions below

1
yergo On BEST ANSWER
<?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.

3
hek2mgl On

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);
});