Change the first word in a sentence in uppercase

I want to convert the first word of a sentence to uppercase, but I don’t know how I would do it. This is what I have so far:

$o = ""; if((preg_match("/ibm/i", $m)) || (preg_match("/hpspecial/i", $m))) { $o = strtoupper($m); } else { $o = ucwords(strtolower($m)); } 

I would like to use uppercase from the hpspecial identifier, where HP is the first part of the sentence, which should be capitalized, but it will be the whole word. How can I make HP only in uppercase?

+4
source share
4 answers

you can tag it ucfirst

ucfirst - create a lowercase first character in uppercase

as

 $foo = 'hello form world'; $foo = ucfirst($foo); 

live exit

edit: to do this in the first uppercase word you can do, for example

 <?php $foo = 'hello form world '; $pieces = explode(" ", $foo); $pieces[0] = strtoupper($pieces[0]); $imp = implode(" ", $pieces); echo $imp; 

live result

+5
source

How about something like this:

 $arr = explode(' '); $arr[0] = strtoupper($arr[0]); echo implode(' ' , $arr); 

I don't know if there is a built-in function, but I think this should work?

+1
source

It seems you really don't have a special template, why not just use preg_replace?

 $search = array('/ibm/i', '/hpspecial/i'); $replace = array('IBM', 'HPspecial'); $string = preg_replace($search, $replace, $string); 

You should still do this because you cannot tell HP from Special (at least in simple ways);

You can use the same approach using str_replace in fact, since you are not using complex templates as far as I can see.

Sometimes the easiest solution is the best

-1
source

you can use a custom function like

 function uc_first_word ($string) { $s = explode(' ', $string); $s[0] = strtoupper($s[0]); $s = implode(' ', $s); return $s; } 

$ string = 'Hello world. This is a test.'; echo $ s = uc_first_word ($ string)

so the output will be

 HELLO world. This is a test 

therefore, the first word in front of the space will be like the upper one for the whole sentence.

-1
source

All Articles