Reputation: 93
I am looking to convert the first word of a sentence into uppercase but unsure how would I go about 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
ID where HP is the first part of the sentence to be capitalized, but this will uppercase the whole sentence. How do I only make HP of the sentence uppercase?
Upvotes: 4
Views: 3117
Reputation: 2040
How about something like this:
$arr = explode(' ');
$arr[0] = strtoupper($arr[0]);
echo implode(' ' , $arr);
I don't know if there's a function built-in, but I think this should work?
Upvotes: 1
Reputation: 11853
you can use 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 output would be
HELLO world. This is a test
so first word before space will be as upper for whole sentence.
Upvotes: -1
Reputation: 4844
Seems that you don't really have a special pattern, why don't just use preg_replace?
$search = array('/ibm/i', '/hpspecial/i');
$replace = array('IBM', 'HPspecial');
$string = preg_replace($search, $replace, $string);
You have to do it like this anyway because you can't really difference HP from Special (at least with simple ways);
You can use the same approach using str_replace actually as you are not using complex patterns as far as I can see.
Sometimes the simplest solution is the best
Upvotes: -1
Reputation: 57322
you can dot his by ucfirst
ucfirst
— Make a string's first character uppercase
like
$foo = 'hello form world';
$foo = ucfirst($foo);
edit: to make it first word upper case you can do like
<?php
$foo = 'hello form world ';
$pieces = explode(" ", $foo);
$pieces[0] = strtoupper($pieces[0]);
$imp = implode(" ", $pieces);
echo $imp;
Upvotes: 6