Captilize every word in ECHO string with PHP

微笑、不失礼 提交于 2020-01-06 15:21:00

问题


Aps if this seems really basic, I'm not a PHP developer.

OK this shows you how to captalize each word in a string Capitalise every word of a string in PHP?

BUT, how do you incorporate this into multiple strings being echoed?

For example I have

<?php echo $prefillTitle, ' ', $prefillFirstname, ' ', $prefillLastname; ?>

How would I ensure each parameter echoes with it's first letter as a capital using the ucwords(). Would it be as simple as this?

<?php echo ucwords($prefillTitle, ' ',  $prefillFirstname, ' ', $prefillLastname; ?>

回答1:


Capitalizing the first letter of every word

ucwords takes one argument and capitalizes the first letter of each word:

echo ucwords($string);

ucwords reference

Note that it will not set the case of the rest of the letters to lowercase, so if you want to be sure that they are, you can use strtolower first as suggested in the comments:

echo ucwords(strtolower($string));

strtolower reference

Capitalizing every letter of every word

If you want to CAPITALIZE THE STRING (which in hindsight I guess you do!), how about using strtoupper:

echo strtoupper($string);

strtoupper reference

There are multiple ways to concatenate your string. You can use the . operator:

$string = $prefillTitle . ' ' . $prefillFirstname . ' ' . $prefillLastname;

Or, as I have done above, you can interpolate the variables:

$string = "$prefillTitle $prefillFirstname $prefillLastname";



回答2:


<?php

$str="$prefillTitle,  $prefillFirstname, $prefillLastname";

echo ucwords($str) ?>



回答3:


The way you try to concatenate your string is not valid, change the , into . and try again:

<?php echo ucwords($prefillTitle . ' ' . $prefillFirstname . ' ' . $prefillLastname); ?>

This should work.

Documentation: http://php.net/ucwords

The function ucwords only accepts 1 parameter as a string.



来源:https://stackoverflow.com/questions/20199222/captilize-every-word-in-echo-string-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!