Friday, 3 June 2016

PHP – CAPITALIZE FIRST LETTER OF EVERY SENTENCE FOR PROPER FORMATTING

Here’s an extremely useful snippet of code that will properly format sentences with capitalization. Actually, what the code really does is capitialize every letter AFTER a full-stop (period). Here’s an example of what the code will do…

Before:

Hello This Is An Example Of A Sentence Which Has Odd Capitalization Which You May Want Fixing. tHere Are Problems With This Method, Which I Will disclose Shortly. If You Know How To Improve THis Code Please Let Me Know.

After:

Hello this is an example of a sentence which has odd capitalization which you may want fixing. There are problems with this method, which i will disclose shortly. If you know how to improve this code please let me know.
1
2
3
4
5
6
7
8
9
10
11
//define string
$string = "Hello This Is An Example Of A Sentence Which Has Odd Capitalization Which You May Want Fixing. tHere Are Problems With This Method, Which I Will disclose Shortly. If You Know How To Improve THis Code Please Let Me Know.";
 
//first we make everything lowercase, and then make the first letter if the entire string capitalized
$string = ucfirst(strtolower($string));
 
//now we run the function to capitalize every letter AFTER a full-stop (period).
$string = preg_replace_callback('/[.!?].*?\w/', create_function('$matches', 'return strtoupper($matches[0]);'),$string);
 
//print the result
echo $string;
There you have it. But there are flaws with this code, which you should be aware of.

Recognised problems to consider

This code will only capitalize the first letter of the string and all letters after full-stops (periods). Names, acronyms and countries will become lowercase when they should be capitalized.
Acronyms with full-stops won’t return as they should appear. For example, “e.g.” will return as “e.G.” because the G is directly after a full-stop.
A common problem is the word “I”, it will be returned in lowercase. For example, “You and i may have to make some exceptions”
Solutions
The way I overcome these issues by making rules with the str_replace function. Put these exceptions after the function has run and before printing the results. This isn’t an ideal solution for large lumps of data as there would be a lot of exceptions, but it’s useful for a manageable data size. You could, however, create your own function(s) to make the clean up process quicker and easier to handle large data.

Possible solutions

1
2
3
4
5
6
7
8
9
 
//to overcome the e.G. problem
$string = str_replace("e.G.","e.g.", $string);
 
//to overcome the lowercase i problem
$string = str_replace(" i "," I ", $string);
 
//to overcome the acronym problem
$string = str_replace("dps","DPS", $string);

0 comments:

Post a Comment