1

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Mark
  • 39
  • 5

3 Answers3

1

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

icy
  • 1,468
  • 3
  • 16
  • 36
  • is non-regex code more efficient then? as I had not considered this. thanks – Mark Jul 24 '19 at 21:40
  • How many words you have to modify? I think it could be negligible for few words. You may also measure this for your specific case: https://stackoverflow.com/a/6245978/1403785 – icy Jul 24 '19 at 21:50
0

You may use

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

See the PHP demo

The ^(?![eiux])[a-z] 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).

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • This works a treat, thanks Wiktor! However, using your existing code, do you know how I would Capitalise the first words in a string which have no specified break or space in them eg. mylongstring to MyLongString?? Presumably this wouldn't be possible without some kind of code link to check a dictionary of words. – Mark Jul 24 '19 at 21:47
  • @Mark Not sure it is not possible. It actually is already a different question. – Wiktor Stribiżew Jul 24 '19 at 21:52
0

If the first character could be other than a letter then check with an array range from a-z 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]);
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87