1

I have been really trying to do some pretty basic work in PHP as I am beginner to PHP but I wasn't really able to achieve my goal. What I want to do is that I have strings like..! Mixed Types :

THIS IS A SENTENCE
tHis Is a SEnTenCe

I really tried with ucwords function in php but that didn't gave the exact result as ucwords focus just on first alphabets of every word and do not focus on other remaining characters in word..What I want really is to get some sort of this fixed type of strings from each and every mixed type of strings..!

Like :

This Is A Sentence

Or May be I didn't check it properly..So if anyone can guide me in the right path.That would be great.!

Umair Shah
  • 2,305
  • 2
  • 25
  • 50
  • what if you have a string such as `THIS IS A SENTENCE FROM the Us-of-A`? `ucwords(strtolower` will fail. – Funk Forty Niner Oct 27 '15 at 21:08
  • @Fred-ii- Well..What will be the solution then for extra informations? – Umair Shah Oct 27 '15 at 21:49
  • I did but can you just post that please..will be really helpful.. – Umair Shah Oct 27 '15 at 21:50
  • Well @Fred-ii- What algorithm would you propose that can determine that the `S` in Us-of-A should be capitalized. – AbraCadaver Oct 28 '15 at 01:20
  • @Fred-ii- @AbraCadaver Would it help to do `explode` and then use `foreach` to get result in Capitalized..! ? For Us-of-A ? – Umair Shah Oct 28 '15 at 11:53
  • @AbraCadaver I was merely pointing it out that it would fail if the OP were faced with characters as such (I should have preceeded it with the word "sidenote") ;-). It will require some pretty fancy regex to do this. Umar, I don't know why you unaccepted AbraCadaver's answer. The question should be marked as solved. – Funk Forty Niner Oct 28 '15 at 12:39
  • @Fred-ii- Understood. `Us of A` would be nearly impossible to get US. – AbraCadaver Oct 28 '15 at 14:42
  • @AbraCadaver Pretty much. TBH, I spent the better part of an hour last night trying to figure it out. I thought I had a piece of code already in my library, but alas; I didn't. I upvoted your answer, and hoping OP will re-accept, *cheers* – Funk Forty Niner Oct 28 '15 at 14:44

2 Answers2

4

Convert to lowercase first:

$string = ucwords(strtolower($string));
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
3
<?php
$l = 'tHis Is a SEnTenCe';
echo ucwords(strtolower($l));
?>

Result

This Is A Sentence
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Lucky Chingi
  • 2,248
  • 1
  • 10
  • 15