Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ucwords function with exceptions

Tags:

php

I need some help i have this code that Uppercase the first character of each word in a string with exceptions i need the function to ignore the exception if it's at the beginning of the string:

function ucwordss($str, $exceptions) {
$out = "";
foreach (explode(" ", $str) as $word) {
$out .= (!in_array($word, $exceptions)) ? strtoupper($word{0}) . substr($word, 1) . " " : $word . " ";
}
return rtrim($out);
}

$string = "my cat is going to the vet";
$ignore = array("is", "to", "the");
echo ucwordss($string, $ignore);
// Prints: My Cat is Going to the Vet

this is what im doing:

$string = "my cat is going to the vet";
$ignore = array("my", "is", "to", "the");
echo ucwordss($string, $ignore);
// Prints: my Cat is Going to the Vet
// NEED TO PRINT: My Cat is Going to the Vet
like image 317
Ered Avatar asked Nov 23 '25 10:11

Ered


2 Answers

- return rtrim($out);
+ return ucfirst(rtrim($out));
like image 184
Explosion Pills Avatar answered Nov 25 '25 23:11

Explosion Pills


Something like this:

function ucwordss($str, $exceptions) {
    $out = "";
    foreach (explode(" ", $str) as $key => $word) {
        $out .= (!in_array($word, $exceptions) || $key == 0) ? strtoupper($word{0}) . substr($word, 1) . " " : $word . " ";
    }
    return rtrim($out);
}

Or even easier, before return in your function make strtoupper first letter

like image 36
RiaD Avatar answered Nov 25 '25 22:11

RiaD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!