Bring last three words of a string to the beginning - php

I want to bring the last three words of a string to its beginning. For example, these two variables:
$vari1 = "It is a wonderful goodbye letter that ultimately had a happy ending.";
$vari2 = "The Science Museum in London is a free museum packed with interactive exhibits.";
Should become:
"A happy ending - It is a wonderful goodbye letter that ultimately had."
"With interactive exhibits - The Science Museum in London is a free museum packed."

Exploding, rearranging, and then imploding should work. See the example here
$array = explode(" ", substr($input_string,0,-1));
array_push($array, "-");
for($i=0;$i<4;$i++)
array_unshift($array, array_pop($array));
$output_string = ucfirst(implode(" ", $array)) . ".";

$split = explode(" ",$vari1);
$last = array_pop($split);
$last = preg_replace("/\W$/","",$last);
$sec = array_pop($split);
$first = array_pop($split);
$new = implode(" ",array(ucfirst($first),$sec,$last)) . " - " . implode(" ",$split) . ".";
Or similar should do the trick.

Make sure to love me tender. <3
function switcheroo($sentence) {
$words = explode(" ",$sentence);
$new_start = "";
for ($i = 0; $i < 3; $i++) {
$new_start = array_pop($words)." ".$new_start;
}
return ucfirst(str_replace(".","",$new_start))." - ".implode(" ",$words).".";
}

This will get you the exact same output that you want in only 2 lines of code
$array = explode(' ', $vari1);
echo ucfirst(str_replace('.', ' - ', join(' ', array_merge(array_reverse(array(array_pop($array), array_pop($array), array_pop($array))), $array)))) . '.';

Related

PHP split string to next period (.)

My aim is to split string after every 7 words. If the 7th word has a comma (,), move to the next word with period (.) or exclamation (!)
So far, I've been able to split string by 7 words, but cannot check if it contains commas (,) or move to the next word with . or !
$string = "I have a feeling about the rain, let us ride. He figured I was only joking.";
$explode = explode(" ", $string);
$chunk_str = array_chunk($explode, 7);
for ($x=0; $x<count($chunk_str); $x++)
{
$strip = implode(" ",$chunk_str[$x]);
echo $strip.'<br><br>';
}
I expect
I have a feeling about the rain, let us ride.
He figured I was only joking.
But the actual output is
I have a feeling about the rain,
let us ride. He figured I was
only joking.
Here's one way to do what you want. Iterate through the list of words, 7 at a time. If the 7th word ends with a comma, increase the list pointer until you reach a word ending with a period or exclamation mark (or the end of the string). Output the current chunk. When you reach the end of the string, output any remaining words.
$string = "I have a feeling about the rain, let us ride. He figured I was only joking.";
$explode = explode(' ', $string);
$num_words = count($explode);
if ($num_words < 7) {
echo $string;
}
else {
$k = 0;
for ($i = 6; $i < count($explode); $i += 7) {
if (substr($explode[$i], -1) == ',') {
while ($i < $num_words && substr($explode[$i], -1) != '.' && substr($explode[$i], -1) != '!') $i++;
}
echo implode(' ', array_slice($explode, $k, $i - $k + 1)) . PHP_EOL;
$k = $i + 1;
}
}
echo implode(' ', array_slice($explode, $k)) . PHP_EOL;
Output:
I have a feeling about the rain, let us ride.
He figured I was only joking.
Demo on 3v4l.org

Extract and merge strings between different positions

I'm trying to make this works. I want to replace some parts of a sentence between given positions and then show the full sentence with the changes. With the following code, I'm able to make the changes but I don't know how to put together the rest of the sentence.
I have two arrays, one with the positions where a woman name appears and another one with men names. The code replaces the pronoun "his" by "her" when a woman is before a man between the intervals. The last thing I need is to reconstruct the sentence with the changes made but I don't know how to extract the rest of the sentence (the result, in the example, is from positions 0 to 20 (Maria her dress but) and 36 to 51 (Lorena her dog) but I need to extract from 20 to 36 (Peter his jeans) and 51 to the end (Juan his car) to merge them in their positions).
The result should be: "Maria her dress but Peter his jeans Lorena her dog Juan his car". I'll appreciate any help with this, I've been looking for other similar questions but I found nothing.
<?php
$womenpos = array("0","36"); //these arrays are just examples of positions
$menpos = array("20","51"); //they will change depending on the sentence
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
foreach ($womenpos as $index => $value) {
$value2 = $menpos[$index];
if($value < $value2) {
echo "\nWoman(" . $value . ") is before man(" . $value2 . ")\n";
$end = ($value2 - $value);
$improved = str_replace(' his ', ' her ',
substr($sentence, $value, $end));
echo $improved."\n";
} else {
$improved = "Nothing changed";
echo $improved;
}
}
Ok, how about this:
$womenpos = array("0","36");
$menpos = array("20","51");
$bothpos = array_merge($womenpos,$menpos);
sort ($bothpos);
print_r($bothpos);
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
echo $sentence."\n";
for ($i = 0; $i<sizeof($bothpos); $i++) {
$start = $bothpos[$i];
if ($i ==sizeof($bothpos)-1) {
$end = strlen($sentence);
}
else {
$end = $bothpos[$i+1];
}
$length = $end-$start;
$segment = substr($sentence, $start, $length);
if (in_array($start, $womenpos)) {
$new_segment = str_replace (' his ', ' her ', $segment);
}
else { $new_segment = $segment; }
$improved .= $new_segment;
print "<li>$start-$end: $segment : $new_segment </li>\n";
}
print "<p>Improved: $improved</p>";
This combines the men's and women's position arrays to consider each stretch of text as one that might have an error. If that stretch of text starts at one of the womenpos points, then it changes 'his' to 'her'. If not it leaves it alone.
Does this get you in the direction you want to go in? I hope so!
This approaches the problem differently, but I wonder if it would provide the solution you're looking for:
$sentence = "Maria his dress but Peter his jeans Lorena his dog Juan his car";
$women = array ("Maria", "Lorena");
$words = explode (" ", $sentence);
for ($i=0; $i< sizeof($words); $i++) {
if ($words[$i] == "his" && in_array($words[$i-1], $women)) {
$words[$i] = "her";
}
}
print (join(" ", $words));
This goes through the words one at a time; if the preceding word is in the $women array and the current word is "his", it changes the word to "her". Then it spits out all the words in order.
Does this do what you need, or do you really want a complex string positioning answer?

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

How to echo lines of text vertically in 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>';
}

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