4

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?

brasofilo
  • 25,496
  • 15
  • 91
  • 179
ash
  • 93
  • 5
  • 14
  • Can you give the full original sentence, and what you want it to be converted to? Your question is not very clear to me. – nkkollaw Apr 12 '13 at 10:03

4 Answers4

6

you can dot his by ucfirst

ucfirst — Make a string's first character uppercase

like

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

live output

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;

live result

NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
  • Thanks. But i would like the whole word of the SENTENCE to be uppercase, not the first letter. i know i have to use strtoupper but in my code i have provided it will convert the whole sentence of 'hpspecial' to uppercase, i just would like the FIRST word of the sentence upper – ash Apr 12 '13 at 09:42
1

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?

nkkollaw
  • 1,947
  • 1
  • 19
  • 29
-1

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

aleation
  • 4,796
  • 1
  • 21
  • 35
-1

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.

liyakat
  • 11,825
  • 2
  • 40
  • 46