Count Number Of Words In a Textarea - php

I have a text area that gets input from a PHP script, and I would like to count the number of words or line breaks in the textarea and echo it below the text area.
This is what the code looks like for the textarea.
<textarea name="domains" cols="120" rows="5" style="max-width:100%;">
<?php $output_array = explode(" ",$output);
$count = count($output_array);
for ($i=0;$i<$count;$i++){
echo $output_array[$i]."\n";
}
?>
</textarea><br />
<br>
<?php
preg_match_all("/(\n)/", $_POST['domains'], $matches);
$total_lines = count($matches[0]) + 1;
echo $total_lines;
?>
<br />
I tried using preg_match_all but the output I get is only "1", regardless of how many line breaks are inside the text area.

$str = 'as aa frd sad as
kjhsdf sdkjh
sd sdkjhsdf
sjkldhfh sdfjh sd';
preg_match_all("/\w+/", $str, $matches);
echo 'Words = ' . count($matches[0]);
echo PHP_EOL;
preg_match_all("/\n/", $str, $matches);
echo 'newlines = ' . count($matches[0]);
echo PHP_EOL;
echo 'So number of line is = ' . count($matches[0])+1;
RESULT
Words = 12
newlines = 3
So number of line is = 4

You can do the following:
$arr = array_filter(explode(" ", $input) function($item) {
return !!$item;
});
$count = count($arr) + count(explode("\n", implode(",", $arr)));
This splits the string by space, filters out empty items to avoid issues due to multiple spaces found between words, then glues the array back into a string, splits it by newline and adds the two counts together.

Related

Any way to detect and disociate an HEX color code from a string in PHP?

I am making a server statistics page in PHP and one of my SQL query show the players nickname including his in-game HEX color codes.
e.g of what I get and what I actually want:
#FF0000Nick#00FF00name --> <span id="nickname"><span style="$color[0]">Nick</span><span style="$color[1]">name</span></span>
What i want to do is disociate the colors from the nickname so i can style them in css and make the nickname coloured.
Here is an idea of my actual code, it's basically a table showing other informations but I'll show you the one I use for the nickname:
while($row = mysqli_fetch_array($result)){
$json = $row['data'];
$playerDataTable = json_decode($json);
foreach($playerDataTable as $playerData){
$ingame_nickname = $playerData->nickname;
echo "<div class='playerNames'";
echo "<span>" . $forum_name . "</span>";
echo "<span class='ingame_nickname'>" . $ingame_nickname . "</span>";
echo "</div>";
}
}
Thank you.
I'd suggest you use regular expressions:
$string = "#FF0000Nick#00FF00name";
$tokens = preg_split('/(#[A-Z0-9]{6})/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
$tokens will be an array of 1, 3, or 5 elements; element 0 will be the part of the username before the first hex code, 1 the first hex code (including '#') with 2 being the part of the text having that color, 3 the second hex code with 4 the part of the name colored like that.
If there's 1 hex code only, $tokens will only contain 3 elements. If there isn't any, $tokens will contain a single element, which is the full uncolored nickname.
echo $tokens[0];
for($x = 1; $x < count($tokens); $x = $x + 2) {
$color = $tokens[$x];
$name_token = $tokens[$x + 1];
echo '<span style="color:' . $color . ';">' . $name_token . '</span>';
}
You should really get your coder to make decent JSON. But however, you can use regex with named capture group
<?php
$json = '{ "nickname": "#FF0000Nick#00FF00name" }';
$data = json_decode($json, true);
$garbledData = $data['nickname'];
// (?<firstHex>\#[A-F0-9]{6}) match and name the match 'firstHex' - look for a hash, then letters a-f or numbers 0-9, with a length of 6 characters
// (?<name>.+) match and name the match 'name' - look for absolutely any characters, any amount
// (?<secondHex>\#[A-F0-9]{6}) match and name the match 'secondHex' - look for a hash, then letters a-f or numbers 0-9, with a length of 6 characters
$regex = '/(?<firstHex>\#[A-F0-9]{6})(?<name>.+)(?<secondHex>\#[A-F0-9]{6})/';
preg_match($regex, $garbledData, $matches);
$firstHex = $matches['firstHex'];
$secondHex = $matches['secondHex'];
$name = $matches['name'];
echo $firstHex . "\n";
echo $secondHex . "\n";
echo $name . "\n";
Output:
#FF0000
#00FF00
Nick
Check it out here https://3v4l.org/qo2gc

PHP explode() built-in function not working as I expected

I tried PHP explod() built-in function to explod my text data stored in a mysql database.
here is I tried sample PHP code:
// Get mysql database data(with \n).
$str_in =
'one
two
three
fore
five
six
';
// Convert \n into <br>.
$str = nl2br($str_in);
// Explode $str and wrapped into <p> tags.
$str_exploded = explode("<br><br>",$str);
foreach($str_exploded as $sub_str) {
echo '<p>'.$sub_str.'</p>';
}
Then I got this output.
<p>one<br>
two<br>
three<br>
<br>
fore<br>
five<br>
<br>
six<br>
</p>
but this is not what I'm expected. I want somthing like this.
<p>one<br>
two<br>
three</p>
<p>fore<br>
five</p>
<p>six</p>
how can I achive this? thanks.
What you are trying to do is remove a when its the only thing on the line.
Strreplace should work with the argument "\n" and a replacement of "\n"
You incorrectly presume, that nl2br function replaces "\n" with <br>. In reality it inserts <br /> before the \n. So, \n\n becomes <br />\n<br />\n. Your
explode("<br><br>",$str)
doesn't work as expected.
To fix it I used exploding by \n\n:
Code
<?php
$str_in =
'one
two
three
fore
five
six
';
$str_exploded = preg_split("/(:?\r?\n){2}/",$str_in);
$n = count($str_exploded);
for ($i = 0; $i < $n; ++$i)
{
// Convert \n into <br>.
$str_exploded[$i] = nl2br($str_exploded[$i]);
echo '<p>'.$str_exploded[$i]."</p>";
if ($i !== $n - 1)
{
print "\n\n";
}
}
Output
<p>one<br />
two<br />
three</p>
<p>fore<br />
five</p>
<p>six<br />
</p>

Hide word randomly from a sentence

I have a sentence that I would like to hide a word randomly, for example:
<?php
$sentence = 'My name is Abu Rayane';
?>
How can I proceed to hide a word in that sentence and replace it with a input text, so the user can fill it and then check if it correct word or not? For example:
My name is Abu <input type="text" name="fillBlank"> <br />
<input type="submit" name="check" value="check">
$sentence = 'My name is Abu Rayane';
$sentence = explode(' ', $sentence);
$position = rand(0, count($sentence) - 1);
$answer = $sentence[$position];
$sentence[$position] = '<input type="text" name="fillBlank">';
echo implode(" ", $sentence);
Example: https://eval.in/185829
Edit: make it work if the length of words in unknown
you could use something like this
$word = explode(' ', $sentence);
$word = $word[rand(0, count($sentence) - 1)];
explode function is really useful if you want to break a string. There is also function implode which does the exact opposite
I tried this, I got the answer from your diffenrent codes:
<?php
$sentence = 'My name is Abu Rayane';
$countSentence = str_word_count($sentence);
echo 'Total words '.$countSentence.'<br />';
// get random number from 0 to 4
$rand = rand(0, $countSentence - 1);
// explode sentence
$ex = explode(' ',$sentence);
// get the equivalent word for a rand number
$hide = $ex[$rand];
$z = implode(' ', $ex).'<br />';
echo str_replace($hide, '______', $z);
?>
Tested: https://eval.in/185847

How to explode a string, with spaces and new lines?

I would like to explode a string (separated based on a delimiter and placed into an array), using both a space (" ") and a newline ("\n") as a delimiter.
The method (which I don't think is the best way) is to:
Explode the array by spaces
Remake the string from the array
Explode it again for new lines
MySQL escape the individual elements.
Question: How do I exploded a string by both a space and new line?
Reference to: new line Array
You could just do a
$segments = preg_split('/[\s]+/', $string);
This function will split $string at every whitespace (\s) occurrence, including spaces, tabs and newlines. Multiple sequential white spaces will count as one (e.g. "hello, \n\t \n\nworld!" will be split in hello, and world! only, without empty strings in the middle.
See function reference here.
You can use preg_split to explode the content using multiple delimiter
$pattern = '/[ \n]/';
$string = "something here ; and there, oh,that's all!";
echo '<pre>', print_r( preg_split( $pattern, $string ), 1 ), '</pre>';
Always go from the bigger to the smaller one.
So first split by "\n" and then split by " ".
$data = "This is a test\nAnd something new happens.";
$rows = explode("\n", $data);
$words = array();
foreach($rows as $row) {
$temp = explode(" ", $row);
foreach($temp as $word)
$words[] = $word;
}
Will give you an array with all words in it.
You can use to explode the content using multiple delimiter.
Sample code
<?php
$str = "Brand : Pandora~ Collection : Summer 13~ Colour : Multi~ Gender : Ladies~ Material : Murano Glass~ Our Code : 0573835~ Packaging : Pandora Branded Packaging~ Product Code : 750513~ Product Type : Bead~ Style : Contemporary";
$r1 = explode("~", $str);
$stringtxt = '<table>';
if (count($r1) > 0) {
foreach ($r1 as $value) {
$rows = explode(":", $value);
$stringtxt .= '<tr>';
$stringtxt .= '<td>' . $rows[0] . '</td><td>' . $rows[1] . '</td>';
$stringtxt .= '</tr>';
}
}
$stringtxt .= '</table>';
print $stringtxt;
?>
Output
<table>
<tr><td>Brand </td><td> Pandora</td></tr>
<tr><td> Collection </td><td> Summer 13</td></tr>
<tr><td> Colour </td><td> Multi</td></tr>
<tr><td> Gender </td><td> Ladies</td></tr>
<tr><td> Material </td><td> Murano Glass</td></tr>
<tr><td> Our Code </td><td> 0573835</td></tr>
<tr><td> Packaging </td><td> Pandora Branded Packaging</td></tr>
<tr><td> Product Code </td><td> 750513</td></tr>
<tr><td> Product Type </td><td> Bead</td></tr>
<tr><td> Style </td><td> Contemporary</td></tr>
</table>

Replace text ignoring HTML tags

I have a simple text with HTML tags, for example:
Once <u>the</u> activity reaches the resumed state, you can freely add and remove fragments to the activity. Thus, <i>only</i> while the activity is in the resumed state can the <b>lifecycle</b> of a <hr/> fragment change independently.
I need to replace some parts of this text ignoring its html tags when I do this replace, for example this string - Thus, <i>only</i> while I need to replace with my string Hello, <i>its only</i> while . Text and strings to be replaced are dynamically. I need your help with my preg_replace pattern
$text = '<b>Some html</b> tags with <u>and</u> there are a lot of tags <i>in</i> this text';
$arrayKeys= array('Some html' => 'My html', 'and there' => 'is there', 'in this text' => 'in this code');
foreach ($arrayKeys as $key => $value)
$text = preg_replace('...$key...', '...$value...', $text);
echo $text; // output should be: <b>My html</b> tags with <u>is</u> there are a lot of tags <i>in</i> this code';
Please help me to find solution. Thank you
Basically we're going to build dynamic arrays of matches and patterns off of plain text using Regex. This code only matches what was originally asked for, but you should be able to get an idea of how to edit the code from the way I've spelled it all out. We're catching either an open or a close tag and white space as a passthru variable and replacing the text around it. This is setup based on two and three word combinations.
<?php
$text = '<b>Some html</b> tags with <u>and</u> there are a lot of tags <i>in</i> this text';
$arrayKeys= array(
'Some html' => 'My html',
'and there' => 'is there',
'in this text' =>'in this code');
function make_pattern($string){
$patterns = array(
'!(\w+)!i',
'#^#',
'! !',
'#$#');
$replacements = array(
"($1)",
'!',
//This next line is where we capture the possible tag or
//whitespace so we can ignore it and pass it through.
'(\s?<?/?[^>]*>?\s?)',
'!i');
$new_string = preg_replace($patterns,$replacements,$string);
return $new_string;
}
function make_replacement($replacement){
$patterns = array(
'!^(\w+)(\s+)(\w+)(\s+)(\w+)$!',
'!^(\w+)(\s+)(\w+)$!');
$replacements = array(
'$1\$2$3\$4$5',
'$1\$2$3');
$new_replacement = preg_replace($patterns,$replacements,$replacement);
return $new_replacement;
}
foreach ($arrayKeys as $key => $value){
$new_Patterns[] = make_pattern($key);
$new_Replacements[] = make_replacement($value);
}
//For debugging
//print_r($new_Patterns);
//print_r($new_Replacements);
$new_text = preg_replace($new_Patterns,$new_Replacements,$text);
echo $new_text."\n";
echo $text;
?>
Output
<b>My html</b> tags with <u>is</u> there are a lot of tags <i>in</i> this code
<b>Some html</b> tags with <u>and</u> there are a lot of tags <i>in</i> this text
Here we go. this piece of code should work, assuming you're respecting only twp constraints :
Pattern and replacement must have the same number of words. (Logical, since you want to keep position)
You must not split a word around a tag. (<b>Hel</b>lo World won't work.)
But if these are respected, this should work just fine !
<?php
// Splits a string in parts delimited with the sequence.
// '<b>Hey</b> you' becomes '~-=<b>~-=Hey~-=</b>~-= you' that make us get
// array ("<b>", "Hey" " you")
function getTextArray ($text, $special) {
$text = preg_replace ('#(<.*>)#isU', $special . '$1' . $special, $text); // Adding spaces to make explode work fine.
return preg_split ('#' . $special . '#', $text, -1, PREG_SPLIT_NO_EMPTY);
}
$text = "
<html>
<div>
<p>
<b>Hey</b> you ! No, you don't have <em>to</em> go!
</p>
</div>
</html>";
$replacement = array (
"Hey you" => "Bye me",
"have to" => "need to",
"to go" => "to run");
// This is a special sequence that you must be sure to find nowhere in your code. It is used to split sequences, and will disappear.
$special = '~-=';
$text_array = getTextArray ($text, $special);
// $restore is the array that will finally contain the result.
// Now we're only storing the tags.
// We'll be story the text later.
//
// $clean_text is the text without the tags, but with the special sequence instead.
$restore = array ();
for ($i = 0; $i < sizeof ($text_array); $i++) {
$str = $text_array[$i];
if (preg_match('#<.+>#', $str)) {
$restore[$i] = $str;
$clean_text .= $special;
}
else {
$clean_text .= $str;
}
}
// Here comes the tricky part.
// We wanna keep the position of each part of the text so the tags don't
// move after.
// So we're making the regex look like (~-=)*Hey(~-=)* you(~-=)*
// And the replacement look like $1Bye$2 me $3.
// So that we keep the separators at the right place.
foreach ($replacement as $regex => $newstr) {
$regex_array = explode (' ', $regex);
$regex = '(' . $special . '*)' . implode ('(' . $special . '*) ', $regex_array) . '(' . $special . '*)';
$newstr_array = explode (' ', $newstr);
$newstr = "$1";
for ($i = 0; $i < count ($regex_array) - 1; $i++) {
$newstr .= $newstr_array[$i] . '$' . ($i + 2) . ' ';
}
$newstr .= $newstr_array[count($regex_array) - 1] . '$' . (count ($regex_array) + 1);
$clean_text = preg_replace ('#' . $regex . '#isU', $newstr, $clean_text);
}
// Here we re-split one last time.
$clean_text_array = preg_split ('#' . $special . '#', $clean_text, -1, PREG_SPLIT_NO_EMPTY);
// And we merge with $restore.
for ($i = 0, $j = 0; $i < count ($text_array); $i++) {
if (!isset($restore[$i])) {
$restore[$i] = $clean_text_array[$j];
$j++;
}
}
// Now we reorder everything, and make it go back to a string.
ksort ($restore);
$result = implode ($restore);
echo $result;
?>
Will output Bye me ! No, you don't need to run!
[EDIT] Now supporting a custom pattern, which allows to avoid adding useless spaces.

Categories