Reputation: 4809
How can I use the PHP strtoupper function for the first two characters of a string? Or is there another function for that?
So the string 'hello' or 'Hello' must be converted to 'HEllo'.
Upvotes: 13
Views: 10379
Reputation:
Using preg_replace()
with the e
pattern modifier could be interesting here:
$str = 'HELLO';
echo preg_replace('/^(\w{1,2})/e', 'strtoupper(\\1)', strtolower($str));
EDIT: It is recommended that you not use this approach. From the PHP manual:
Use of this modifier is discouraged, as it can easily introduce security vulnerabilites:
<?php $html = $_POST['html']; // uppercase headings $html = preg_replace( '(<h([1-6])>(.*?)</h\1>)e', '"<h$1>" . strtoupper("$2") . "</h$1>"', $html );
The above example code can be easily exploited by passing in a string such as
<h1>{${eval($_GET[php_code])}}</h1>
. This gives the attacker the ability to execute arbitrary PHP code and as such gives him nearly complete access to your server.To prevent this kind of remote code execution vulnerability the preg_replace_callback() function should be used instead:
<?php $html = $_POST['html']; // uppercase headings $html = preg_replace_callback( '(<h([1-6])>(.*?)</h\1>)', function ($m) { return "<h$m[1]>" . strtoupper($m[2]) . "</h$m[1]>"; }, $html );
As recommended, instead of using the e
pattern, consider using preg_replace_callback()
:
$str = 'HELLO';
echo preg_replace_callback(
'/^(\w{1,2})/'
, function( $m )
{
return strtoupper($m[1]);
}
, strtolower($str)
);
Upvotes: 3
Reputation: 33163
$txt = strtoupper( substr( $txt, 0, 2 ) ).substr( $txt, 2 );
This works also for strings that are less than 2 characters long.
Upvotes: 21
Reputation: 197785
ucfirst
Docs does only the first, but substr access on strings works, too:
$str = ucfirst($str);
$str[1] = strtoupper($str[1]);
Remark: This works, but you will get notices on smaller strings if offset 1 is not defined, so not that safe, empty strings will even be converted to array. So it's merely to show some options.
Upvotes: 1
Reputation:
$string = "hello";
$string{0} = strtoupper($string{0});
$string{1} = strtoupper($string{1});
var_dump($string);
//output: string(5) "HEllo"
Upvotes: 4
Reputation: 34053
This should work strtoupper(substr($target, 0, 2)) . substr($target, 2)
where $target is your 'hello' or whatever.
Upvotes: 1
Reputation: 77976
$str = substr_replace($str, strtoupper($str[0].$str[1]), 1, 2);
Upvotes: 3
Reputation: 360702
Assuming it's just a single word you need to do:
$ucfirsttwo = strtoupper(substr($word, 0, 2)) . substr($word, 2);
Basically, extract the first two characters and uppercase the, then attach the remaining characters.
If you need to handle multiple words in the string, then it gets a bit uglier.
Oh, and if you're using multi-byte characters, prefix the two functions with mb_ to get a multibyte-aware version.
Upvotes: 3