...

View Full Version : Resolved Caps Fix



Deacon Frost
01-07-2010, 11:12 AM
Trying to write a function to fix capitalization in an input field to only allow 1 cap per word, and a max of 4 caps per sentence. I think I'm on the right track, but it's returning a buttload of errors.



function caps_check($string) {
$sentences = split(".", $string);
$newsentences = array();
$newwords = array();

foreach ($sentences as $sentence) {
$words = split(" ", $sentences);
foreach ($words as $word) {
$letters = split($words);
foreach ($letters as $letter) {
if ($letter = strtoupper($letter)) {
$j = $j + 1;
}
}
if ($j > 1) {
$word = strtolower($word);
}
array_push($newwords, $word);
}
if ($j > 4) {
$sentence = strtolower($sentence);
}
array_push($newsentences, $sentence);
}
return join("", $newsentences);
}

Stooshie
01-07-2010, 11:41 AM
Firstly, split() is now deprecated. use explode instead (it's faster anyway).

What are the errors you are getting?

abduraooft
01-07-2010, 11:46 AM
On a quick look, the code
if ($letter = strtoupper($letter)) is wrong! It should be ==
.. and you'd need to reset the value of $j before your loops.

Deacon Frost
01-07-2010, 12:06 PM
On a quick look, the code
if ($letter = strtoupper($letter)) is wrong! It should be ==
.. and you'd need to reset the value of $j before your loops.

Haha ^.^ Thanks guys. The errors I was returning was for the split() and one of the foreach(). I've completely revamped it, but I'm still working on the limiting the number of caps in a sentence.



function caps_check($string) {
$newwords = array();
$words = explode(" ", $string);

foreach ($words as $word) {
$letters = str_split($word);
foreach ($letters as $letter) {
if ($letter == strtoupper($letter)) {
$j = $j + 1;
}
}
if ($j >= 4) {
$word = strtolower($word);
}
array_push($newwords, $word);
unset($j);
}
foreach ($newwords as $value) {
$str = $str." ".$value;
}
return $str;
}

Deacon Frost
01-07-2010, 12:32 PM
Now it just returns 'Array' >.< :P.



function caps_check($string) {
$sentences = explode(".", $string);
$newsentences = array();

foreach ($sentences as $sentence) {
$newwords = array();
$words = explode(" ", $sentence);
foreach ($words as $word) {
$letters = str_split($word);
foreach ($letters as $letter) {
if ($letter == strtoupper($letter)) {
$j = $j + 1;
}
}
if ($j >= 4) {
$word = strtolower($word);
$word = ucfirst($word);
}
$word = $word." ";
array_push($newwords, $word);
}
if ($j >= 20) {
$sentence = strtolower($sentence);
$sentence = ucfirst($sentence);
}
array_push($newsentences, $newwords);
$j = 0;
}
foreach ($newsentences as $val) {
if ($str) {
$str = $str.". ".$val;
}
else {
$str = $val;
}
}
return $str;
}

If I put in "Test. Test."

It returns "Array. Array. Array" >.<. Lol.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum