开发者

In a paragraph how to make every first letter of the word into Capital letter using PHP

I am having a paragraph and i want to make every first letter of the word into a capital letter using PHP.

ex:

converting every first letter into capital letter.

should convert into

Converting Every First Letter Into Capital Letter.

Than开发者_运维技巧k You


If this is strictly for presentation, you can also use CSS for this:

  • capitalize: transforms the first character in each word to uppercase; all other characters remain unaffected — they’re not transformed to lowercase, but will appear as written in the document.

Example:

p {
    text-transform: capitalize
}

See

  • http://reference.sitepoint.com/css/text-transform


There's a function for that — ucwords():

echo ucwords("converting every first letter into capital letter.");


For converting every first letter capital use the below code

Ex)

<?php
$data = "converting every first letter into capital letter.";
echo ucwords($data);
?>

Output: Converting Every First Letter Into Capital Letter.

For converting the first letter capital in a sentence use the below code Ex)

<?php
$data = "converting every first letter into capital letter.";
echo ucfirst($data);
?>

Output: Converting every first letter into capital letter.

For converting the first letter capital in all sentence use the below code. Ex)

<?php
$string = "this is a first message. this is a second message. this is a third message! hope this helps.";

$string = strtolower($string);
echo preg_replace('/(^|[\.!?]"?\s+)([a-z])/e', '"$1" . ucfirst("$2")', $string); 
?>

Output: This is a first message. This is a seconde message. This is a third message! Hope this helps.


Nithin Raja, your example is great! Below the code adjusted for >= PHP7 Thanks!

$string = "Olá, tudo bem? Esta é a minha segunda frase.\nAqui já estou na terceira. E agora encerrando o texto.";
$capitalize = preg_replace_callback('/(^|[\.!?]"?\s+)([a-z])/', function($parte){return $parte[1] . ucfirst($parte[2]);}, $string);
echo nl2br($capitalize);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜