How to echo lines of text vertically in PHP? - php

I got this problem somewhere, and I want to know how to solve this using PHP. Given this text:
$str = '
PHP is a
widely-used
general-purpose
server side
scripting
language
';
How to echo the text vertically like the given below:
g
e
n
e
w r s
i a e
d l r s
P e - v c l
H l p e r a
P y u r i n
- r p g
i u p s t u
s s o i i a
e s d n g
a d e e g e
I will select the simpler and more elegant code as the answer.

As others have already demonstrated, array_map is able to do the flip over which is basically the main problem you need to solve. The rest is how you arrange the code. I think your version is very good because it's easy to understand.
If you're looking more to some other extreme, handle with care:
$str = 'PHP is a
widely-used
general-purpose
server side
scripting
language';
$eol = "\n";
$turned = function($str) use ($eol) {
$length = max(
    array_map(
        'strlen',
        $lines = explode($eol, trim($str))
    )
);
$each = function($a, $s) use ($length) {
    $a[] = str_split(
        sprintf("%' {$length}s", $s)
    );
    return $a;
};
return implode(
    $eol,
    array_map(
        function($v) {
            return implode(' ', $v);
        },
        call_user_func_array(
            'array_map',
            array_reduce($lines, $each, array(NULL))
        )
    )
);
};
echo $turned($str), $eol;
Gives you:
g
e
n
e
w r s
i a e
d l r s
P e - v c l
H l p e r a
P y u r i n
- r p g
i u p s t u
s s o i i a
e s d n g
a d e e g e
This fixes the output of the other answer, which was incorrect (now fixed).

The code below will print $str vertically.
$lines = preg_split("/\r\n/", trim($str));
$nl = count($lines);
$len = max(array_map('strlen', $lines));
foreach ($lines as $k => $line) {
$lines[$k] = str_pad($line, $len, ' ', STR_PAD_LEFT);
}
for ($i = 0; $i < $len; $i++) {
for ($j = 0; $j < $nl; $j++) {
echo $lines[$j][$i].($j == $nl-1 ? "\n" : " ");
}
}

I took some of the code from #bsdnoobz and simplified it. I'm using \n as a line break because I work on a Mac and \r\n doean work here.
$lines = preg_split("/\n/", trim($str));
$len = max(array_map('strlen', $lines));
$rows = array_fill(0,$len,'');
foreach ($lines as $k => $line) {
foreach (str_split(str_pad($line, $len, ' ', STR_PAD_LEFT)) as $row => $char){
$rows[$row] .= $char;
}
}
echo implode("\n",$rows)."\n";

$a = explode(PHP_EOL, trim($str));
$h = max(array_map('strlen', $a));
$w = count($a);
$m = array_map('str_split', array_map('sprintf', array_fill(0, $w, "%{$h}s"), $a));
$t = call_user_func_array('array_map', array_merge(array(null), $m));
echo implode(PHP_EOL, array_map('implode', array_fill(0, $h, ' '), $t)), PHP_EOL;
PHP_EOL should be replaced with "\n", "\r\n" or '<br/>' where appropriate. The whole code after the first line could easily become one big expression, only its readability would suffer a little bit ;-)
$a is the array of lines, $h is the final height, $w is the final width, $m is the matrix of characters (after padding the strings), $t is the transposed matrix.
The array_fill(0, $h, ' '), on the last line can simply be omitted if the space between columns is not needed. On the other hand, not printing trailing space characters can be achieved like this:
echo implode(PHP_EOL, array_map('rtrim', array_map('implode', array_fill(0, $h, ' '), $t))), PHP_EOL;
I have taken the question as an excercise in avoiding explicit loops (which are usually more expensive than loops inside PHP functions, although in this case the advantage could be lost). The important trick here is the matrix transposition, which I have taken from this answer by Codler
Anyhow, the complexity of the whole algorithm is O(width × height), just like the one of most algorithms on this page, except for those that repeatedly concatenate strings in order to obtain the lines, whose complexity is O(width² × height)

I'll give this a shot:
$arrlines = explode(PHP_EOL, trim($str));
$max = max(array_map('strlen', $arrlines));
foreach($arrlines as $val)
$arrlines = str_pad($val,$max," ",STR_PAD_LEFT);
for($x=0;$x<$max;$x++){
for($y=0;$y<count($arrlines);$y++)
$string .= strlen(trim($arrlines[$y][$x])) > 0 ? $arrlines[$y][$x]." ":" ";
$string .= "\n";
}
echo '<pre>'.$string.'</pre>';
Line numbers:
save the string per line in an array $arrlines separated by the PHP constant PHP_EOL
get the maximum string length and save it to $max
loop for every element of $arrlines, then
add padding to the left of the string to make its string length equal to $max
for lines 5-9, nested loop to save the $arrline[$y][$x] to $string, and line 10 outputs the result.
Result can be found here.

Here is simple code any one can understand this code
$str = '
PHP is a
widely-used
general-purpose
server side
scripting
language
';
$lines = array();
$sentences = explode("\n\n",$str);
foreach($sentences as $sentence){
if($sentence != ""){
$each_lines = explode("\n",$sentence);
foreach($each_lines as $each_line){
if($each_line != ""){
$lines[] = $each_line;
}
}
$lines[] = "\t";
}
}
$before_sort = $lines;
usort($lines, "cmp_len");
$big_length = strlen($lines[0]);
foreach($before_sort as $key=>$arr){
$this_length = strlen($arr);
if($this_length < $big_length){
$no_of_letters = $big_length - $this_length;
$text = "";
for($i=0;$i<$no_of_letters;$i++){
$text .= " ";
}
$text .= $before_sort[$key];
$before_sort[$key] = $text;
}
}
$temp = array();
echo "<table>";
for($i=0;$i<$big_length;$i++){
echo "<tr>";
foreach($before_sort as $arr){
echo "<td>";
echo str_replace("\t"," ",$arr[$i]);
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
function cmp_len($a, $b){
return (strlen($a) < strlen($b));
}

Check this answer:
<?php
$str = 'PHP is a
widely-used
general-purpose
server side
scripting
language';
function getVerticalString($str){
$str = preg_split('/\r|\n/',$str);
$maxlength = 0;
$totalstr = count($str);
for($i=0;$i<$totalstr;$i++){
if($maxlength<strlen($str[$i])){
$maxlength = strlen($str[$i]);
}
}
$strings = array();
for($i=0;$i<$maxlength;$i++){
$strings[$i] = "";
for($j=0;$j<$totalstr;$j++){
$temp = strlen($str[$j])-($maxlength-$i);
if($temp>=0){
$strings[$i] .= substr($str[$j],$temp,1);
}
else{
$strings[$i] .= " ";
}
}
}
return implode("\r",$strings);
}
echo "<pre>".getVerticalString($str)."</pre>";
this outputs:
g
e
n
e
w rs
i ae
d lr s
Pe -v cl
Hl pe ra
Py ur in
- r pg
iu ps tu
ss oi ia
e sd ng
ad ee ge
As per your requirements. :)

I wouldn't really call it shorter, but line count is less ;-)
$nr_lines = count($lines = preg_split('/\r?\n/', trim($str)));
$maxlen = max($lengths = array_map('strlen', $lines)); // get line lengthts and maximum
$line_ptrs = array_fill(0, $nr_lines, 0); // last character position per line
for ($j = 0; $j != $maxlen; ++$j) {
for ($i = 0; $i != $nr_lines; ++$i) {
// $maxlen - $lengths[$i] indicates where printing start for this line
echo $j >= $maxlen - $lengths[$i] ? $lines[$i][$line_ptrs[$i]++] : ' ';
}
echo "\n";
}
It does the padding and printing in the same inner loop, aided by the $line_ptrs and $lengths array to keep track of which character to print next.
Benchmark
Based on 10,000 iterations, this code performs 19% better than the first answer.

Please note that the length of a string and the number of elements in an array are cached by PHP per variable. Calling strlen or count repeatedly has only the performance penalty of an empty function call (on subsequent calls, the length or count are not measured twice internally by PHP).
This works with a Mac (\r), Linux (\n) or Windows (\r\n) input string, and/or with an empty input string, and/or with a one line input string, and outputs with a prefered line delimiter (default is PHP_EOL):
function matrix_vertical_align_bottom($str, $strEOL=PHP_EOL)
{
$arrLines=explode("\n", $str);
$nMaxLength=max(array_map("strlen", $arrLines));
$nRotatedWidth=count($arrLines)+strlen($strEOL);
//allocate once
$strRotated=str_pad(
"",
$nRotatedWidth*$nMaxLength-strlen($strEOL),
str_repeat(" ", count($arrLines)).$strEOL
);
foreach($arrLines as $nRotatedColumnIndex=>$strLine)
{
$nRotatedVerticalPadding=$nMaxLength-strlen($strLine);
for($nColumnIndex=strlen($strLine)-1; $nColumnIndex>=0; $nColumnIndex--)
$strRotated[$nRotatedWidth*($nColumnIndex+$nRotatedVerticalPadding)+$nRotatedColumnIndex]=$strLine[$nColumnIndex];
}
return $strRotated;
}
echo matrix_vertical_align_bottom(preg_replace("/(\r\n|\r|\n)/", "\n", trim($str)));
The performance is pretty good, the above algorithm is just translating coordinates while rotating the string by 90 degrees. There is no memory re-allocation because of string expanding provoked by padding individual lines (for input strings with lots of lines, this would be a performance hit).
HTML output is not assumed, nl2br(htmlspecialchars( )) when outputting should do the trick + a mono spaced font.

It's like the old saying goes:
If it can be done without regex, try it anyway.
Some people, when confronted with a problem, think
“I know, I'll use regular expressions.” Now they have zero problems.
"I took the [road] less traveled by" - Robert Frost
With so many similar techniques on this page, I thought I'd offer a fresh perspective. Here is a technique by which the input string is consumed within a loop and the last character (if it exists) of each line is added to the output array as a space-delimited string. The loop is broken when the entire input string consists of whitespace characters. I did not benchmark it, but I would be curious to hear any comparisons if anyone is inclined to provide their findings.
Code: (Demo)
$result = [];
while (!ctype_space($string)) {
$line = [];
$string = preg_replace_callback(
"~.$|^$~m",
function($m) use(&$line) {
$line[] = $m[0] === '' ? ' ' : $m[0];
return '';
},
$string,
);
array_unshift($result, implode(' ', $line));
}
echo implode("\n", $result);

My function to rotate text without any language construct loops:
/**
* Rotates text
*
* #param string $str String to rotate
*
* #return string Rotated string
*/
function rotateText($str)
{
$lines = explode(PHP_EOL, $str);
$lengths = array_map('strlen', $lines);
$maxLength = max($lengths);
$lines = array_map(function ($line) use ($maxLength) {
return str_pad($line, $maxLength, ' ', STR_PAD_LEFT);
}, $lines);
$chars = array_map('str_split', $lines);
array_unshift($chars, null);
$rotatedLines = call_user_func_array('array_map', $chars);
$rotatedText = join(PHP_EOL, array_map('join', $rotatedLines));
return $rotatedText;
}
echo "<pre>", rotateText($str), "</pre>";

Here's my shot at it. Couldn't figure out how to do it without the nested loop.
$lines = array_map('strrev', explode("\r\n", trim($str)));
$new = array();
foreach(range(0, max(array_map('strlen', $lines))) as $i){
foreach($lines as $line){
$new[$i] .= (!empty($line[$i]) ? $line[$i] . ' ' : ' ');
}
}
echo implode("\r\n", (array_slice(array_reverse($new), 1)));

Try this one,
$str = 'PHP is a
widely-used
general-purpose
server side
scripting
language';
$strArr = explode("\r\n", $str);
$max =max(array_map('strlen', $strArr));
for($i=0; $i< $max;$i++)
{
for($x=0;$x < count($strArr); $x++)
{
$strVal = $strArr[$x];
$y = $i -($max - strlen($strVal));
$vertical .= strlen(trim($strVal[$y]))<> 0 ? $strVal[$y]." " : " ";
}
$vertical .="\n";
}
echo "<pre>".$vertical;

The best and simplest way :)
<style type="text/css">
#heading{
/* vertical text css */
width:1em;
text-transform:uppercase;
}
</style>
<h1 align="center" id="heading">h e l l o</h1>
DEMO

$a= 'HelloWorld!';
$b=strlen($a);
for($i=0;$i<$b;$i++){
echo $c=substr($a,$i,1).'<br>';
}

Related

Explode string by one or more spaces and new lines

How can I explode a string by one or more spaces or tabs?
Example:
A B C
D E F
G H I
J K L
M N O
I have successfully tokenize on spaces and tab's with this code:
$parts = preg_split('/\s+/', $str);
but the issue rises when there is new line.
I want to make this an array so that i can run mysqlquery as well.
If you want to get a matrix of characters, split by newline first:
<?php
$str = "A B\tC\nD E\tF";
$parts = preg_split("/\n+/", $str);
foreach($parts as $key => $line)
{
$parts[$key] = preg_split("/\s+/", $line);
}
//output
$n = count($parts);
for ($i = 0; $i < $n; ++$i)
{
$m = count($parts[$i]);
for ($j = 0; $j < $m; ++$j)
{
print $parts[$i][$j]." ";
}
print "\n";
}
Output:
A B C
D E F

PHP: Shift characters of string by 5 spaces? So that A becomes F, B becomes G etc

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 );

reorder / rewrap bbcodes

I'm trying to reorder the BBCodes but I failed
so
[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶b̶]̶[̶/̶u̶]̶[̶/̶i̶]̶ ̶-̶ ̶w̶r̶o̶n̶g̶ ̶o̶r̶d̶e̶r̶ ̶ ̶
I̶ ̶w̶a̶n̶t̶ ̶i̶t̶ ̶t̶o̶ ̶b̶e̶:̶ ̶
̶[̶b̶]̶[̶i̶]̶[̶u̶]̶f̶o̶o̶[̶/̶u̶]̶[̶/̶i̶]̶[̶/̶b̶]̶ ̶-̶ ̶r̶i̶g̶h̶t̶ ̶o̶r̶d̶e̶r̶
PIC:
I tried with
<?php
$string = '[b][i][u]foo[/b][/u][/i]';
$search = array('/\[b](.+?)\[\/b]/is', '/\[i](.+?)\[\/i]/is', '/\[u](.+?)\[\/u]/is');
$replace = array('[b]$1[/b]', '[i]$1[/i]', '[u]$1[/u]');
echo preg_replace($search, $replace, $string);
?>
OUTPUT: [b][i][u]foo[/b][/u][/i]
any suggestions ? thanks!
phew, spent awhile thinking of the logic to do this. (feel free to put it in a function)
this only works for the scenario given. Like other users have commented it's impossible. You shouldn't be doing this. Or even on server side. I'd use a client side parser just to throw a syntax error.
supports [b]a[i]b[u]foo[/b]baa[/u]too[/i]
and bbcode with custom values [url=test][i][u]foo[/url][/u][/i]
Will break with
[b] bold [/b][u] underline[/u]
And [b] bold [u][/b] underline[/u]
//input string to be reorganized
$string = '[url=test][i][u]foo[/url][/u][/i]';
echo $string . "<br />";
//search for all opentags (including ones with values
$tagsearch = "/\[([A-Za-z]+)[A-Za-z=._%?&:\/-]*\]/";
preg_match_all($tagsearch, $string, $tags);
//search for all close tags to store them for later
$closetagsearch = "/(\[\/([A-Za-z]+)\])/is";
preg_match_all($closetagsearch, $string, $closetags);
//flip the open tags for reverse parsing (index one is just letters)
$tags[1] = array_reverse($tags[1]);
//create temp var to store new ordered string
$temp = "";
//this is the last known position in the original string after a match
$last = 0;
//iterate through each char of the input string
for ($i = 0, $len = strlen($string); $i < $len; $i++) {
//if we run out of tags to replace/find stop looping
if (empty($tags[1]) || empty($closetags[1]))
continue;
//this is the part of the string that has no matches
$good = substr($string, $last, $i - $last);
//next closing tag to search for
$next = $closetags[1][0];
//how many chars ahead to compare against
$scope = substr($string, $i, strlen($next));
//if we have a match
if ($scope === "$next") {
//add to the temp variable with a modified
//version of an open tag letter to become a close tag
$temp .= $good . substr_replace("[" . $tags[1][0] . "]", "/", 1, 0);
//remove the first key/value in both arrays
array_shift($tags[1]);
array_shift($closetags[1]);
//update the last known unmatched char
$last += strlen($good . $scope);
}
}
echo $temp;
Please also note: it might be the users intention to nest the tags out of order :X

Add space after every 4th character

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

PHP Word Length Density / Count calc for a string

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
}
?>

Categories