Home > Backend Development > PHP Tutorial > How Can I Efficiently Convert a String to

How Can I Efficiently Convert a String to

Susan Sarandon
Release: 2024-12-24 01:55:10
Original
762 people have browsed it

How Can I Efficiently Convert a String to

Capitalize First Letter of Each Word and Correct Case for Others

The question presents a situation where some string characters are improperly capitalized. The goal is to convert the string to title case, i.e., capitalize the first letter of each word and lowercase the rest.

While using ucfirst($str) to convert the first character of the string to uppercase is common, it does not handle other characters correctly.

A more efficient approach is to use a combination of ucwords() and strtolower().

$str = "tHis iS a StRinG thAt NeEds ProPer CapiTilization";
$newStr = ucwords(strtolower($str));
echo $newStr; // Hello World!
Copy after login

This code first lowers all characters in the string using strtolower() and then capitalizes the first letter of each word using ucwords(). Combining these functions effectively corrects the capitalization of the entire string.

The above is the detailed content of How Can I Efficiently Convert a String to. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template