简体   繁体   中英

How to change specific first Letter in string to Capital using PHP?

If the first character of my string contains any of the following letters, then I would like to change the first letter to Uppercase: (a,b,c,d,f,g,h,j,k,l,m,n,o,p,q,r,s,t,v,w,y,z) but not (e,i,u,x).

For example,

  • luke would become Luke
  • egg would stay the same as egg
  • dragon would become Dragon

I am trying to acheive this with PHP, here's what I have so far:

<?php if($str("t","t"))
 echo ucfirst($str);
  else
   echo "False";
    ?>

My code is simply wrong and it doesn't work and I would be really grateful for some help.

Without regex:

function ucfirstWithCond($str){
    $exclude = array('e','i','u','x');

    if(!in_array(substr($str, 0, 1), $exclude)){
        return ucfirst($str);
    }

    return $str;
}

$test = "egg";
var_dump(ucfirstWithCond($test)); //egg
$test = "luke";
var_dump(ucfirstWithCond($test)); //Luke

Demo: http://sandbox.onlinephpfunctions.com/code/c87c6cbf8c616dd76fe69b8f081a1fbf61cf2148

You may use

$str = preg_replace_callback('~^(?![eiux])[a-z]~', function($m) {
    return ucfirst($m[0]);
}, $str);

See the PHP demo

The ^(?![eiux])[az] regex matches any lowercase ASCII char at the start of the string but e , u , i and x and the letter matched is turned to upper inside the callback function to preg_replace_callback .

If you plan to process each word in a string you need to replace ^ with \\b , or - to support hyphenated words - with \\b(?<!-) or even with (?<!\\S) (to require a space or start of string before the word).

If the first character could be other than a letter then check with an array range from az that excludes e,i,u,x :

if(in_array($str[0], array_diff(range('a','z'), ['e','i','u','x']))) {
    $str[0] = ucfirst($str[0]);
}

Probably simpler to just check for the excluded characters:

if(!in_array($str[0], ['e','i','u','x'])) {
    $str[0] = ucfirst($str[0]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM