I want to get the count of characters from the following words in the string. For example, if my input is I am John then the output must be like this:
1 // count of 'I'
4 // count of 'I am'
9 // count of 'I am John'
I use the code like this in PHP for this process:
$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);
$i =0;
while ($i<=$count_words){
$word_length =0;
$k=0;
while($k<=$i){
$word_length = strlen($words[$k-1]);
$word_length = $word_length + strlen($words[$k]);
$k++;
}
$word_length = $word_length + $i; // there is "$i" means "space"
echo $word_length.'<br/>';
$i++;
}
But it return the output like this:
1
4
8
7
Why ? Where is my error ? What does my code must be like ?
Thanks in advance!
<?php
$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);
$i =0;
while ($i<$count_words){
if($i==0) {
$wordsc[$i] = strlen($words[$i]);
} else {
$wordsc[$i] = strlen($words[$i])+1+$wordsc[$i-1];
}
echo $wordsc[$i]."<br>";
$i++;
}
?>
Your error is here:
$i =0;
while ($i<=$count_words){
//....
}
$count_words is 3, but you iterate 4 times because of <=. Use < instead.
You were looping through to many words. When you use count it returns the number of elements in an array. Remember an array starts at 0.
$word_length + strlen($words[$k - 1]); // You were subtracting 1 I think you were trying to cater for the count offest but you are subtracting -1 from 0 causing the first word to be missed.
CODE SNIPPET START
//Set up the words
$string = 'I am John';
$words = explode(' ',$string);
$count_words = count($words);
//Loop through the words
$i =0;
while ($i<$count_words){
$word_length =0;
$k=0;
$debugString = '';
//Loop through all the previous words to the current
while($k<= $i){
//dont really need this since were adding the word length later
//$word_length = strlen($words[$k]);
//if you -1 from 0 you will get an undefined offest notice. You
//want to look at your current word
$word_length = $word_length + strlen($words[$k]);
//A bit of debugging you can delete this once you have seen the results
$debugString = $debugString ." ".$words[$k];
$k++;
}
$word_length = $word_length + $i ; // there is "$i" means "space"
//Added the debugString for debugging so remove it once you have seen the results
echo $word_length." " .$debugString.' <br/>';
$i++;
}
CODE SNIPPET END
I am happy to provide you with a completely different approach for generating your desired data in a very direct way. (Demo of what is to follow)
var_export(preg_match_all('/ |$/','I am John',$out,PREG_OFFSET_CAPTURE)?array_column($out[0],1):'failure');
Output:
array (
0 => 1,
1 => 4,
2 => 9,
)
Determining the length of each word-incremented substring is effectively the same as determining the offset of each trailing space, or on the final word - the full string length.
preg_match_all() has a built-in "flag" for this: PREG_OFFSET_CAPTURE
preg_match_all() before any array manipulation will output this:
array (
0 =>
array (
0 =>
array (
0 => ' ', // <-- the space after 'I' matched by ' '
1 => 1,
),
1 =>
array (
0 => ' ', // <-- the space after 'am' matched by ' '
1 => 4,
),
2 =>
array (
0 => '', // <-- the end of the string (after 'John') matched by '$'
1 => 9,
),
),
)
array_column() is used on the $out[0] to extract only the offset values (omitting the useless blank and empty strings).
Here is another, totally different method:
array_reduce(preg_split('/(?= )/',$string),function($carry,$item){echo $carry+=strlen($item)," "; return $carry;},0);
output: 1 4 9
This splits the string on the "zero-width" string that is followed by a space. This means that in the exploding process, the spaces are not lost -- this maintains the string and substring lengths for simple addition.
Related
I have a number that a user will put into a form - 12 digits. Every second digit needs to be replaced - if the digit is:
1 then make it 5
2 then make it 1
3 then make it 6
4 then make it 2
5 then make it 7
6 then make it 3
7 then make it 8
8 then make it 4
0 and 9 stay the same.
So for example:
343608111218 will end up being 383307121417.
Here is an example of what I'm currently doing, but I think it is long winded. This is just for the first number, so I'm assuming I could do something else?
$_POST['number'] = '343608111218';
preg_match_all('~(\d)~', $_POST['number'], $pregs);
if($pregs[1][1] === "1") {
$one = 5;
}
elseif ($pregs[1][1] === "2"){
$one = 1;
}
elseif ($pregs[1][1] === "3"){
$one = 6;
}
elseif ($pregs[1][1] === "4"){
$one = 2;
}
elseif ($pregs[1][1] === "5"){
$one = 7;
}
elseif ($pregs[1][1] === "6"){
$one = 3;
}
elseif ($pregs[1][1] === "7"){
$one = 8;
}
elseif ($pregs[1][1] === "8"){
$one = 4;
}
$rep1 = (array_replace($pregs[1],array(1=>$one)));
If there is a way that I can reduce the amount of code, I would be very grateful. Thank you.
One way of doing it is with preg_replace_callback, passing the match of 2 digits in a row and using strtr to replace the 2nd digit appropriately:
$_POST['number'] = '343608111218';
echo preg_replace_callback('~(\d)(\d)~', function ($m) {
return $m[1] . strtr($m[2], '12345678', '51627384');
}, $_POST['number']);
Output:
323304151114
This is based on the description you gave on how to do replacements. However if your expected output reflects the correct way to do the replacements, the replacements have to be the other way around, which is just a question of changing the order of parameters to strtr:
echo preg_replace_callback('~(\d)(\d)~', function ($m) {
return $m[1] . strtr($m[2], '51627384', '12345678');
}, $_POST['number']);
Output:
383307121417
Demo on 3v4l.org
As you are replacing each digit with another, create a lookup string and use the number as the index to the array, all the positions 0-9 are set - even if they are the same value. As the value is a string, you can just use the value as the position of the string and replace it directly...
$value = $_POST['number'];
$trans = "0516273849";
for ( $i = 1; $i < strlen($value); $i+=2 ) {
$value[$i] = $trans[$value[$i]];
}
echo $value;
Edit:
To achieve what is the 'desired' output (although only a guess as to what this should be) you can change the line to...
$trans = "0246813579";
$transform = array(
0 => 0,
1 => 5,
2 => 1,
3 => 6,
4 => 8,
5 => 7,
6 => 3,
7 => 8,
8 => 4,
9 => 9
);
$number = '343608111218';
$num = array_map('intval', str_split($number));
$i = 1;
foreach ($num as $key => $value) {
if (0 == ($i % 2)) {
echo $transform[$value];
} else {
echo $value;
}
$i++;
}
To modernize and refine Nick's regex script, use \K to eliminate the use of capture groups. Arrow function syntax helps to make the script more concise. (Demo)
echo preg_replace_callback(
'/.\K\d/',
fn($m) => strtr($m[0], '12345678', '51627384'),
$_POST['number']
);
Nigel's answer is optimized for performance. Despite counting the string length on every iteration and unnecessarily replacing certain numbers with the same number, it will perform very swiftly because it only makes iterated calls of count(). Because all characters in the input string and the translation string are expected to be single-byte characters, the cooresponding number in the translation string can be accessed by its offset. Here's my version of Nigel's script (Demo)
$value = '343608111218';
$trans = '0516273849';
for ($i = 1, $len = strlen($value); $i < $len; $i += 2) {
$value[$i] = $trans[$value[$i]];
}
echo $value;
Mujuonly's answer can be boiled down a little further. $var & 1 is a bitwise odd check which is just as cryptic as !($var % 2), but is slightly faster (not noticeably). Casting each character as an integer is not necessary and using a string-type translation source is a more succinct technique. (Demo)
$number = '343608111218';
$trans = '0516273849';
foreach (str_split($number) as $i => $d) {
if ($i & 1) {
$number[$i] = $trans[$d];
}
}
echo $number;
How can I shift characters of string in PHP by 5 spaces?
So say:
A becomes F
B becomes G
Z becomes E
same with symbols:
!##$%^&*()_+
so ! becomes ^
% becomes )
and so on.
Anyway to do this?
The other answers use the ASCII table (which is good), but I've got the impression that's not what you're looking for. This one takes advantage of PHP's ability to access string characters as if the string itself is an array, allowing you to have your own order of characters.
First, you define your dictionary:
// for simplicity, we'll only use upper-case letters in the example
$dictionary = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
Then you go through your input string's characters and replace each of them with it's $position + 5 in the dictionary:
$input_string = 'STRING';
$output_string = '';
$dictionary_length = strlen($dictionary);
for ($i = 0, $length = strlen($input_string); $i < $length; $i++)
{
$position = strpos($dictionary, $input_string[$i]) + 5;
// if the searched character is at the end of $dictionary,
// re-start counting positions from 0
if ($position > $dictionary_length)
{
$position = $position - $dictionary_length;
}
$output_string .= $dictionary[$position];
}
$output_string will now contain your desired result.
Of course, if a character from $input_string does not exist in $dictionary, it will always end up as the 5th dictionary character, but it's up to you to define a proper dictionary and work around edge cases.
Iterate over characters and, get ascii value of each character and get char value of the ascii code shifted by 5:
function str_shift_chars_by_5_spaces($a) {
for( $i = 0; $i < strlen($a); $i++ ) {
$b .= chr(ord($a[$i])+5);};
}
return $b;
}
echo str_shift_chars_by_5_spaces("abc");
Prints "fgh"
Iterate over string, character at a time
Get character its ASCII value
Increase by 5
Add to new string
Something like this should work:
<?php
$newString = '';
foreach (str_split('test') as $character) {
$newString .= chr(ord($character) + 5);
}
echo $newString;
Note that there is more than one way to iterate over a string.
PHP has a function for this; it's called strtr():
$shifted = strtr( $string,
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"FGHIJKLMNOPQRSTUVWXYZABCDE" );
Of course, you can do lowercase letters and numbers and even symbols at the same time:
$shifted = strtr( $string,
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!##$%^&*()_+",
"FGHIJKLMNOPQRSTUVWXYZABCDEfghijklmnopqrstuvwxyzabcde5678901234^&*()_+!##$%" );
To reverse the transformation, just swap the last two arguments to strtr().
If you need to change the shift distance dynamically, you can build the translation strings at runtime:
$shift = 5;
$from = $to = "";
$sequences = array( "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz",
"0123456789", "!##$%^&*()_+" );
foreach ( $sequences as $seq ) {
$d = $shift % strlen( $seq ); // wrap around if $shift > length of $seq
$from .= $seq;
$to .= substr($seq, $d) . substr($seq, 0, $d);
}
$shifted = strtr( $string, $from, $to );
I have a sentence as an input.
I want to be able to calculate the total score of a sentence (a=1, b=2, c=3), according to the letters that form each word.
Also, if a sentence has a double letter i want to double its value.
Finally, I want to filter out characters different from a-z.
Code (Edited)
$words = "Try to do this";
$letters = str_split($words);
$value = '0 a b c d e f g h i j k l m n o p q r s u v w x y z';
$value = explode(' ',$value);
$value1 = array_flip($value);
$result = array_intersect($letters, $value);
This is something I started but can't finish and I post it just to see if my logic is correct!
I reworked your code & think this will work as expected. I have edited this code so it can now account for double score items properly. Note that the $double_score_array has only single letters, but the regex has {2} to indicate that 2 letters in a row should be looked at. Comments are in place to explain each stage:
// Set the '$words' string.
$words = "Try to do thiis.";
// Set an array for double score items.
$double_score_array = array('i');
// Init the '$raw_results' array
$raw_results = array();
// Create a '$value_array' using the range of 'a' to 'z'
$value_array = range('a','z');
// Prepend a '0' onto the '$value_array'
array_unshift($value_array, 0);
// Flip the '$value_array' so the index/key values can be used for scores.
$value_array_flipped = array_flip($value_array);
// Filter out any character that is not alphabetical.
$words = preg_replace('/[^a-zA-Z]/', '', strtolower($words));
// Let's roll through the double score items.
foreach ($double_score_array as $double_score_letter) {
preg_match('/' . $double_score_letter . '{2}/', $words, $matches);
$double_score_count = count($matches);
// With double score items accounted, let's get rid of the double score item to get normal scores.
$words = preg_replace('/' . $double_score_letter . '{2}/', '', $words);
}
// Split the '$words' string into a '$letters_array'
$letters_array = str_split($words);
// Now let's set the value for the double score items.
$raw_results[] = (($value_array_flipped[$double_score_letter] * 2) * $double_score_count);
// Roll through the '$letters_array' and assign values.
foreach ($letters_array as $letter_key => $letter_value) {
$raw_results[] = $value_array_flipped[$letter_value];
}
// Filter out the empty values from '$raw_results'.
$filtered_results = array_filter($raw_results);
// Run an 'array_sum()' on the '$filtered_results' to get a final score.
$final_results = array_sum($filtered_results);
// Echo the score value in '$final_results'
echo 'Score: ' . $final_results;
// Dump the '$filtered_results' for debugging.
echo '<pre>';
print_r($filtered_results);
echo '</pre>';
EDIT In the comments the original poster states that the code above does not double the score. Unclear about that since—as per the example—the letter i is the 9th letter of the alphabet. So the score would be 9. So wouldn’t double score be 18? Or so you mean it should be 36 meaning double the score of the two individual i items?
If “double score” actually means taking the score of the two individual items & doubling it, then simply go to this portion of the code:
// Now let's set the value for the double score items.
$raw_results[] = (($value_array_flipped[$double_score_letter] * 2) * $double_score_count);
And change the 2 to 4 like so to effectively double the score of double letter ietms:
// Now let's set the value for the double score items.
$raw_results[] = (($value_array_flipped[$double_score_letter] * 4) * $double_score_count);
ANOTHER EDIT Okay, I think I understand the original posters request. Specifically when they ask, “Also, if a sentence has a double letter i want to double its value.” Which I—and others interpreted as two letters in a row such as ii, but seems that if those two letters show up in a sentence only then would the score be doubled. So I reworked the logic to account for any two instances of i showing up in a sentence. And since it’s unclear what should happen if more than 2 i’s show up in a sentence, I set logic to account for cases like that; those extra i’s just get a single value. Adding my new version. Compare & contrast with the first version above. You should now be able to do whatever you need to.
// Set the '$words' string.
$words = "Try to do thiiis.";
// Set an array for double score items.
$double_score_array = array('i');
// Set a double score multiplier.
$double_score_multiplier = 2;
// Init the '$raw_results' array
$raw_results = array();
// Create a '$value_array' using the range of 'a' to 'z'
$value_array = range('a','z');
// Prepend a '0' onto the '$value_array'
array_unshift($value_array, 0);
// Flip the '$value_array' so the index/key values can be used for scores.
$value_array_flipped = array_flip($value_array);
// Filter out any character that is not alphabetical.
$words = preg_replace('/[^a-zA-Z]/', '', strtolower($words));
// Let's roll through the double score items.
$double_score_count = $non_double_count = 0;
foreach ($double_score_array as $double_score_letter) {
$double_score_regex = sprintf('/%s{1}/', $double_score_letter);
preg_match_all($double_score_regex, $words, $matches);
$count = count($matches[0]);
// We only want to double the score for the first two letters found.
if ($count >= 2) {
$double_score_count = 2;
}
// This handles the accounting for items past the first two letters found.
$non_double_count += ($count - 2);
// This handles the accounting for single items less than the first two letters found.
if ($count < 2) {
$non_double_count += $count;
}
// With double score items accounted, let's get rid of the double score item to get normal scores.
$words = preg_replace($double_score_regex, '', $words);
}
// Split the '$words' string into a '$letters_array'
$letters_array = str_split($words);
// Now let's set the value for the double score items.
if ($double_score_count > 0) {
$raw_results[] = (($value_array_flipped[$double_score_letter] * $double_score_multiplier) * $double_score_count);
}
// And get the values of items that are non-double value.
if ($non_double_count > 0) {
$raw_results[] = $value_array_flipped[$double_score_letter] * $non_double_count;
}
// Roll through the '$letters_array' and assign values.
foreach ($letters_array as $letter_key => $letter_value) {
$raw_results[] = $value_array_flipped[$letter_value];
}
// Filter out the empty values from '$raw_results'.
$filtered_results = array_filter($raw_results);
// Run an 'array_sum()' on the '$filtered_results' to get a final score.
$final_results = array_sum($filtered_results);
// Echo the score value in '$final_results'
echo 'Score: ' . $final_results;
// Dump the '$filtered_results' for debugging.
echo '<pre>';
print_r($filtered_results);
echo '</pre>';
// Input string
$str = 'Try to do this';
// Remove irrelevant characters, convert to lowercase
$str = preg_replace('/[^a-z]/', '', strtolower($str));
// Create a function to determine the value of a character
function my_char_value($char) {
return ord($char) - 96;
}
// Convert the string to an array and apply our function to each element
$arr = array_map('my_char_value', str_split($str));
// Add each array element to determine subtotal
$sum = array_sum($arr);
// Double the sum if two "i"s are present in the string
if (preg_match('/i.*?i/', $str)) {
$sum *= 2;
}
print $sum;
I have found out a better solution
Check this code out
<?php
/**
* Script to calculate the total score of a sentence (a=1, b=2, c=3), according to the letters that form each word.
* Also, if a sentence has a double letter i want to double its value.
* Finally, I want to filter out characters different from a-z.
*
* Author: Viswanath Polaki
* Created: 5-12-2013
*/
//array to define weights
$weight = array(
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
'e' => 5,
'f' => 6,
'g' => 7,
'h' => 8,
'i' => 9,
'j' => 10,
'k' => 11,
'l' => 12,
'm' => 13,
'n' => 14,
'o' => 15,
'p' => 16,
'q' => 17,
'r' => 18,
's' => 19,
't' => 20,
'u' => 21,
'v' => 22,
'w' => 23,
'x' => 24,
'y' => 25,
'z' => 26
);
//your sentance
$sentance = "My name is Viswanath Polaki. And my lucky number is 33";
$asentance = array();
$strlen = strlen($sentance);
//converting sentance to array and removing spaces
for ($i = 0; $i < $strlen; $i++) {
if ($sentance[$i] != " ")
$asentance[] = strtolower($sentance[$i]);
}
$sumweights = array();
//calculation of weights
foreach ($asentance as $val) {
if (key_exists($val, $weight)) {
$sumweights[$val] += $weight[$val];
} else {
$sumweights['_unknown'][] = $val;
}
}
ksort($sumweights);//sorting result
echo "<pre>";
print_r($sumweights);
echo "</pre>";
?>
How about:
function counter($string) {
// count the number of times each letter occurs, filtering out anything other than a-z
$counts = array_count_values(
str_split(
preg_replace('/[^a-z]/iS', '', strtolower($string))
)
);
// convert the counts to Caeser ciphers (a => 1, aa => 2, bb => 4, etc.)
array_walk(
$counts,
function (&$value, $letter) {
$value = $value * (ord($letter) - 96);
}
);
// sum up the encodings
$sum = array_sum($counts);
// if there's a double i, double again
if (preg_match('/ii/iS', $string)) {
$sum *= 2;
}
return $sum;
}
Test cases
echo counter("i"); // = 9
echo counter("ii"); // = 36
echo counter("abc0"); // = 6
echo counter("aabc0"); // = 7
echo counter("aabbcc00"); // = 12
echo counter("Try to do this"); // = 173
I want to add a space to some output after every 4th character until the end of the string.
I tried:
$str = $rows['value'];
<? echo substr($str, 0, 4) . ' ' . substr($str, 4); ?>
Which just got me the space after the first 4 characters.
How can I make it show after every 4th ?
You can use chunk_split [docs]:
$str = chunk_split($rows['value'], 4, ' ');
DEMO
If the length of the string is a multiple of four but you don't want a trailing space, you can pass the result to trim.
Wordwrap does exactly what you want:
echo wordwrap('12345678' , 4 , ' ' , true )
will output:
1234 5678
If you want, say, a hyphen after every second digit instead, swap the "4" for a "2", and the space for a hyphen:
echo wordwrap('1234567890' , 2 , '-' , true )
will output:
12-34-56-78-90
Reference - wordwrap
Have you already seen this function called wordwrap?
http://us2.php.net/manual/en/function.wordwrap.php
Here is a solution. Works right out of the box like this.
<?php
$text = "Thiswordissoverylong.";
$newtext = wordwrap($text, 4, "\n", true);
echo "$newtext\n";
?>
Here is an example of string with length is not a multiple of 4 (or 5 in my case).
function space($str, $step, $reverse = false) {
if ($reverse)
return strrev(chunk_split(strrev($str), $step, ' '));
return chunk_split($str, $step, ' ');
}
Use :
echo space("0000000152748541695882", 5);
result: 00000 00152 74854 16958 82
Reverse mode use ("BVR code" for swiss billing) :
echo space("1400360152748541695882", 5, true);
result: 14 00360 15274 85416 95882
EDIT 2021-02-09
Also useful for EAN13 barcode formatting :
space("7640187670868", 6, true);
result : 7 640187 670868
short syntax version :
function space($s=false,$t=0,$r=false){return(!$s)?false:(($r)?trim(strrev(chunk_split(strrev($s),$t,' '))):trim(chunk_split($s,$t,' ')));}
Hope it could help some of you.
On way would be to split into 4-character chunks and then join them together again with a space between each part.
As this would technically miss to insert one at the very end if the last chunk would have exactly 4 characters, we would need to add that one manually (Demo):
$chunk_length = 4;
$chunks = str_split($str, $chunk_length);
$last = end($chunks);
if (strlen($last) === $chunk_length) {
$chunks[] = '';
}
$str_with_spaces = implode(' ', $chunks);
one-liner:
$yourstring = "1234567890";
echo implode(" ", str_split($yourstring, 4))." ";
This should give you as output:
1234 5678 90
That's all :D
The function wordwrap() basically does the same, however this should work as well.
$newstr = '';
$len = strlen($str);
for($i = 0; $i < $len; $i++) {
$newstr.= $str[$i];
if (($i+1) % 4 == 0) {
$newstr.= ' ';
}
}
PHP3 Compatible:
Try this:
$strLen = strlen( $str );
for($i = 0; $i < $strLen; $i += 4){
echo substr($str, $i, 4) . ' ';
}
unset( $strLen );
StringBuilder str = new StringBuilder("ABCDEFGHIJKLMNOP");
int idx = str.length() - 4;
while (idx > 0){
str.insert(idx, " ");
idx = idx - 4;
}
return str.toString();
Explanation, this code will add space from right to left:
str = "ABCDEFGH" int idx = total length - 4; //8-4=4
while (4>0){
str.insert(idx, " "); //this will insert space at 4th position
idx = idx - 4; // then decrement 4-4=0 and run loop again
}
The final output will be:
ABCD EFGH
Given a text, how could I count the density / count of word lengths, so that I get an output like this
1 letter words : 52 / 1%
2 letter words : 34 / 0.5%
3 letter words : 67 / 2%
Found this but for python
counting the word length in a file
Index by word length
You could start by splitting your text into words, using either explode() (as a very/too simple solution) or preg_split() (allows for stuff that's a bit more powerful) :
$text = "this is some kind of text with several words";
$words = explode(' ', $text);
Then, iterate over the words, getting, for each one of those, its length, using strlen() ; and putting those lengths into an array :
$results = array();
foreach ($words as $word) {
$length = strlen($word);
if (isset($results[$length])) {
$results[$length]++;
}
else {
$results[$length] = 1;
}
}
If you're working with UTF-8, see mb_strlen().
At the end of that loop, $results would look like this :
array
4 => int 5
2 => int 2
7 => int 1
5 => int 1
The total number of words, which you'll need to calculate the percentage, can be found either :
By incrementing a counter inside the foreach loop,
or by calling array_sum() on $results after the loop is done.
And for the percentages' calculation, it's a bit of maths -- I won't be that helpful, about that ^^
You could explode the text by spaces and then for each resulting word, count the number of letters. If there are punctuation symbols or any other word separator, you must take this into account.
$lettercount = array();
$text = "lorem ipsum dolor sit amet";
foreach (explode(' ', $text) as $word)
{
#$lettercount[strlen($word)]++; // # for avoiding E_NOTICE on first addition
}
foreach ($lettercount as $numletters => $numwords)
{
echo "$numletters letters: $numwords<br />\n";
}
ps: I have not proved this, but should work
You can be smarter about removing punctuation by using preg_replace.
$txt = "Sean Hoare, who was first named News of the World journalist to make hacking allegations, found dead at Watford home. His death is not being treated as suspiciou";
$txt = str_replace( " ", " ", $txt );
$txt = str_replace( ".", "", $txt );
$txt = str_replace( ",", "", $txt );
$a = explode( " ", $txt );
$cnt = array();
foreach ( $a as $b )
{
if ( isset( $cnt[strlen($b)] ) )
$cnt[strlen($b)] += 1;
else
$cnt[strlen($b)] = 1;
}
foreach ( $cnt as $k => $v )
{
echo $k . " letter words: " . $v . " " . round( ( $v * 100 ) / count( $a ) ) . "%\n";
}
My simple way to limit the number of words characters in some string with php.
function checkWord_len($string, $nr_limit) {
$text_words = explode(" ", $string);
$text_count = count($text_words);
for ($i=0; $i < $text_count; $i++){ //Get the array words from text
// echo $text_words[$i] ; "
//Get the array words from text
$cc = (strlen($text_words[$i])) ;//Get the lenght char of each words from array
if($cc > $nr_limit) //Check the limit
{
$d = "0" ;
}
}
return $d ; //Return the value or null
}
$string_to_check = " heare is your text to check"; //Text to check
$nr_string_limit = '5' ; //Value of limit len word
$rez_fin = checkWord_len($string_to_check,$nr_string_limit) ;
if($rez_fin =='0')
{
echo "false";
//Execute the false code
}
elseif($rez_fin == null)
{
echo "true";
//Execute the true code
}
?>