PHP - A Word Count Script
I've been trying to come up with a way to accurately count a word string which includes punctuation marks. I've got close but the white-space is causing a problem. I have used a couple of functions such as str_replace and explode and I can now get an accurate count for texts with most punctuation and 'normal' white space. BUT.. If I put in three extra spaces between words the count adds 1 to the total.
$words2 = str_replace("-", "", $string); // strips a hypen $words3 = str_replace(' ', ' ', $words2); // strips double spaces $words = explode(' ', $words3); This is obviously NOT a script - rather a string of text being passed through three functions to cleanse it. But as you can see it will strip two white spaces when they occur but no more. So three, four, five etc. will be counted as extra words. What else could I try to give me an accurate count? I am very raw at php. thanks Richard Similar TutorialsI am writing a function to count the words that have been typed into a text box. I originally had it working when I first wrote it but it was counting all of the punctuation as a word so I I tried adding some code to eliminate that. Now it is not working. Could someone help me? Here is my code Code: [Select] function count_words($description){ $word_count = 0; $description = trim(preg_replace("/\s+/"," ",$description)); $word_array = explode(" ", $description); for($i=0; $i < count($word_array); $i++){ if (preg_match("[0-9A-Za-z]", $word_array[$i])) { $word_count++; } return $word_count; } } How to COUNT the number of records (pulled from a db)which contains the word "APPROVED". This code doesn't work though. $result1; $result2; $result3; $approvedApplicants = COUNT($result1=='Approved', $result2=='Approved', $result3=='Approved') echo ($approvedApplicants) I'm using the code below to on echo certain words based on their index/key value, this works fine however, im trying to only do this in exploded quotes... the problem is, exploding quotes turns the portion into an array which cant be passed to str_word_count... how can i do the same thing only inside quotes. So that hello world "this is a test" would become: Code: [Select] Hello World This [0] => Is [1] => a [2] => Test [3] Im trying to always remove say the 4th word in quotations, or maybe the 3rd and 4th, whatever i want to omit i leave out from the echo, so echo $data[0].' '.$data[3].'; would output "This Test" omitting "Is A" Code: [Select] $data = 'hello world "this is a test"'; $data = str_word_count($data, 1); echo $data[1].' '.$data[2].' '.$data[0]; This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=343070.0 is this possible? Hi guys, I need your help. I am trying to insert the rows in the mysql database as I input the values in the url bar which it would be like this: Code: [Select] www.mysite.com/testupdate.php?user=tester&pass=test&user1=tester&email=me@shitmail.com&ip=myisp However i have got a error which i don't know how to fix it. Error: Column count doesn't match value count at row 1 <?php session_start(); define('DB_HOST', 'localhost'); define('DB_USER', 'mydbusername'); define('DB_PASSWORD', 'mydbpassword'); define('DB_DATABASE', 'mydbname'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($var){ return mysql_real_escape_string(strip_tags($var)); } $username = clean($_GET['user']); $password = clean($_GET['pass']); $adduser = clean($_GET['user1']); $email = clean($_GET['email']); $IP = clean($_GET['ip']); if($username == '') { $errmsg_arr[] = 'username is missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'PASSWORD is missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; echo implode('<br />',$errmsg_arr); } else { $sql = "INSERT INTO `members` (`username`,`email`,`IP`) VALUES ('$adduser','$email','$IP')"; if (!mysql_query($sql,$link)) { die('Error: ' . mysql_error()); } echo "The information have been updated."; } ?> Here's the name of the columns i have got in my database: Code: [Select] username IP I have input the correct columns names, so I can't correct the problem I am getting. Please can you help? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=331562.0 Why am I getting this error when there are 3 Fields with 3 values? Column count doesn't match value count at row 1 Code: [Select] $sql5="INSERT INTO participants (participant_name, team_no, sport) VALUES ('".implode("','$_POST[team]'),('",$_POST['participant_name'])."','$_POST[team]','$sport')"; Anyone can help me? <?php $tbl_name="menu"; $kategorije = mysql_query("SELECT * FROM $tbl_name WHERE Left(menu_name, 1) BETWEEN 'A' AND 'M' ORDER BY menu_name ASC"); if (!$kategorije) { die("Database query failed: " . mysql_error()); } while ($row=mysql_fetch_array( $kategorije )) { echo "<div id=lista-header><h4>{$row["menu_name"]}</h4></div>"; $id_sub=$row['id_menu']; $podkategorije = mysql_query("SELECT * FROM submenu WHERE id_menu=$id_sub ORDER BY sub_name ASC", $connection); if (!$podkategorije) { die("Database query failed: " . mysql_error()); } echo "<ul class=\"pod\">"; while ($pod=mysql_fetch_array( $podkategorije )) { echo "<li><a href=index.php?=podkate?".$pod["id_sub"]." class=black>{$pod["sub_name"]}</a><hr size=1 align=left width=100px color=#cccccc></li>"; } echo "</ul>"; } ?> In this way, I get list with categories and hes subcategories. How to count how many subcategories have each categories, and count how many articles have each categories? Example (I wanna get this kind of look): Categories name (3) subcategoriesname (2) subcategoriesname (4) subcategoriesname (7) Categories name (5) subcategoriesname (1) subcategoriesname (14) subcategoriesname (9) subcategoriesname (2) subcategoriesname ( Categories name (2) subcategoriesname (28) subcategoriesname (17) Where the numbers represent how many categories and sub-items have articles I have this code below the browser shows correct data but when i export to word I see $proc output not the switch data like on the the browser page
How should code be written to show the same on word doc .
I'm new to this learning by trial and error Please go easy on me .
Thanks
<td> <? Hey guys i found this script that works great for what i need .. se i have this script that i did for my body (loan application) now i would like to export the info in a word doc <?php $ExcelFileName="test.doc"; header("Content-type: application/x-ms-download"); header("Content-Disposition: attachment; filename=$ExcelFileName"); header('Cache-Control: public'); $content=<<<EOD echo 'php'; whatever you want to write here including a php script it will be included in a string and then go in the output for a doc file EOD; echo $content; ?> so im trying to eco all the content in the database.. i tryed all the DB connection is there.. ao i place this after the (echo 'php' while($info = mysql_fetch_array($fileLIST)){; echo $info['PERS_F_NAME']; }; i get this? Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/autosspe/public_html/admin/loan/word.php on line 21 I'm going to post the code that I am currently using and then explain what I'm trying to do. I hope I can explain it well enough. <?php if (!isset($_POST['submit'])) { echo'<leftmargin="0" topmargin="0" rightmargin="0" bottommargin="0"> <center><form name="fairlistlist" method="POST" action="'.$_SERVER['PHP_SELF'].'"> <TABLE width="450" height="119" border=0 cellPadding=3 cellSpacing=2 bgcolor="#fff568"> <TBODY> <TR> <TD class=mainText width="100"><b>Event Name</b></TD> <TD width="305" class=frmInput> <INPUT class=mainFormBox style="WIDTH: 320px" type="text" name=" fairname"></TD> </TR> <TR> <TD class=mainText width="100"><B>Event Address</B></TD> <TD class=frmInput> <INPUT name="fairadd" type="text" class=mainFormBox id="fairadd" style="WIDTH: 320px"></TD> </TR> <TR> <TD class=mainText width="100"><b>Event City</b></TD> <TD class=frmInput> <INPUT name="faircity" type="text" class=mainFormBox id="faircity" style="WIDTH: 320px"></TD> </TR> <TR> <TD class=mainText width="100"><b>Event County</b></TD> <TD class=frmInput> <INPUT name="faircty" type="text" class=mainFormBox id="faircty" style="WIDTH: 320px"></TD> </TR> <TR> <TD class=mainText width="100"><b>Event State</b></TD> <TD class=frmInput> <INPUT name="fairstate" type="text" class=mainFormBox id="fairstate" style="WIDTH: 320px"></TD> </TR> <TR> <TD class=mainText width="100"><b>Event Country</b></TD> <TD class=frmInput> <INPUT name="fairctry" type="text" class=mainFormBox id="fairctry" style="WIDTH: 320px"></TD> </TR> <TR> <TD class=mainText width="100"><b>Event Opening Date</b></TD> <TD class=frmInput> <INPUT name="fairopen" type="text" class=mainFormBox id="fairopen" style="WIDTH: 320px"></TD> </TR> <TR> <TD class=mainText width="100"><b>Event Closing Date</b></TD> <TD class=frmInput> <INPUT name="fairclose" type="text" class=mainFormBox id="fairlose" style="WIDTH: 320px"></TD> </TR> <TR> <TD class=mainText width="100"><b>Event Contact Email</b></TD> <TD class=frmInput> <INPUT name="fairmail" type="text" class=mainFormBox id="fairmail" style="WIDTH: 320px"></TD> </TR> <TR> <TD class=mainText width="100"><b>Event Website</b></TD> <TD class=frmInput> <INPUT name="fairweb" type="text" class=mainFormBox id="fairweb" style="WIDTH: 320px"></TD> </TR> <TR> <TD class=frmDescription width="56"> </TD> <TD class=frmInput> <div align="right"> <input type="submit" name="submit" value="Add my Event" /> </div></TD> </TR> </TBODY> </TABLE> </form></center> </body>'; //note that I added a new field called submit and it's hidden .. } else { /*I added addslashes() so it escape any special char in the form .. if you want to show your inserted record , you need to use stripslashes() to remove any slashes from the record .. this is only to avoid some security problems in the query ..*/ $fairname=trim(addslashes($_POST['fairname'])); $fairadd=trim(addslashes($_POST['fairadd'])); $faircity=trim(addslashes($_POST['faircity'])); $faircty=trim(addslashes($_POST['faircty'])); $fairstate=trim(addslashes($_POST['fairstate'])); $fairctry=trim(addslashes($_POST['fairctry'])); $fairopen=trim(addslashes($_POST['fairopen'])); $fairclose=trim(addslashes($_POST['fairclose'])); $fairmail=trim(addslashes($_POST['fairmail'])); $fairweb=trim(addslashes($_POST['fairweb'])); include("Connections/local.php"); $link = mysql_connect($hostname_local,$username_local, $password_local) or die("Could not connect"); mysql_select_db('fair123') or die("Could not select database"); $insert=mysql_query("INSERT INTO events (fairidnum, fairname, fairadd, faircity, faircty, fairstate, fairctry, fairopen, fairclose, fairmail, fairweb) VALUES('NULL', '$fairname', '$fairadd', '$faircity', '$faircty','$fairstate', '$fairctry','$fairopen', '$fairclose', '$fairmail', '$fairweb')")or die('couldn\'t Insert record into database :'.mysql_error()); header( 'Location: event_added.php' ) ; } ?> Especially look at the code part here $insert=mysql_query("INSERT INTO events (fairidnum, fairname, fairadd, faircity, faircty, fairstate, fairctry, fairopen, fairclose, fairmail, fairweb) VALUES('NULL', '$fairname', '$fairadd', '$faircity', '$faircty','$fairstate', '$fairctry','$fairopen', '$fairclose', '$fairmail', '$fairweb')")or die('couldn\'t Insert record into database :'.mysql_error()); header( 'Location: event_added.php' ) ; } ?> this is where I am having problems it was reading echo your record has been successfully added to the database What I want is for it to open up a new page with my menu and my css and all that good crap to a page where it will read the following Your information has been added to our database We have added Event name = "whatever the event's name was" Event address = "address:" so on and so on for all the fields in my form that was submitted to the database. with just using the echo command it always opened to just a blank page no formatting and no css as well as no all important links Can you please tell me what I'm doing wrong or where I can find a good guideline that Is easy to understand on how to do this? Thanks in advance Oh also I don't care if that page get's indexed by google or yahoo or not actually prefer it don't get indexed to be honest Hi guys, I'm trying to export records from php to ms word which appends text + image. i have got this code from http://www.thaicreate.com/php/php-word.application-addpicture.html Code: [Select] <html> <head> <title>ThaiCreate.Com PHP Word.Application Tutorial</title> </head> <body> <? $wdColorDarkRed = "&H80"; $wdAlignParagraphCenter = "1"; $wdAlignParagraphLeft = "0"; $wdParagraph = "4"; $wdHorizontalPositionMargin = "0"; $wdTableLeft = "-999998"; $wdCollapseEnd = "0"; $Wrd = new COM("Word.Application"); $DocName = "MyDoc/MyWord.doc"; //$strPath = realpath(basename(getenv($_SERVER["SCRIPT_NAME"]))); // C:/AppServ/www/myphp $Wrd->Application->Visible = False; $WrdDoc = $Wrd->Documents->Add(); $MyRange1 = $WrdDoc->Paragraphs->Add->Range; $MyRange1->ParagraphFormat->Alignment = $wdAlignParagraphCenter; $MyRange1->Font->Name = "Verdana"; $MyRange1->Font->Size = "30"; $MyRange1->Font->Bold = True; $MyRange1->InsertBefore(chr(13).chr(13)."www.ThaiCreate.Com".chr(13)."Version 2009"); $MyRange1->InlineShapes->AddPicture(realpath("thaicreate-2009.gif")); //$WrdDoc->InlineShapes->AddPicture(realpath("thaicreate-2009.gif")); //$WrdDoc->Shapes->AddPicture(realpath("thaicreate-2009.gif"),0,0,MyRange1); //$WrdDoc->Shapes->AddPicture(realpath("thaicreate-2009.gif"),0,0,Wrd->Selection->Range); $MyRange2 = $WrdDoc->Paragraphs->Add->Range; $MyRange2->ParagraphFormat->Alignment = $wdAlignParagraphCenter; $MyRange2->Font->Name = "Verdana"; $MyRange2->Font->Size = "15"; $MyRange2->Font->Bold = True; $MyRange2->InsertBefore(chr(13).chr(13)."PHP,ASP and ASP.NET Tutorial"); $MyRange2->InlineShapes->AddPicture(realpath("doc.gif")); $MyRange3 = $WrdDoc->Paragraphs->Add->Range; $MyRange3->ParagraphFormat->Alignment = $wdAlignParagraphCenter; $MyRange3->Font->Name = "Verdana"; $MyRange3->Font->Size = "10"; $MyRange3->Font->Bold = True; $MyRange3->Font->Color = $wdColorDarkRed; $MyRange3->Underline = True; $MyRange3->InsertBefore(chr(13).chr(13).chr(13).chr(13)."All Rights Reserved"); //$WrdDoc->SaveAs($strPath."/".$DocName); $WrdDoc->SaveAs(realpath($DocName)); $Wrd->Application->Quit; $Wrd = null; ?> Word Created <a href="<?=$DocName?>">Click here</a> to Download. </body> </html> This is the best code i've found so far that guides on how to format the text in ms word via PHP. All set to go but one thing that I am trying to accomplish : to have a clickable email address (hyperlink) in the same ms word file. i have got this code somewhere from the net: Code: [Select] $MyRange3->Hyperlinks->Add({range}, 'http://www.google.com', '','',' hyperlink text to display'); // where {range} refers to as anchor according to that website this methods could be found in ms word visual basic editor (Alt+F11) then object browser (F2) when i replace the {range} above with let say variable $MyRange3. Code: [Select] $MyRange3->Hyperlinks->Add($MyRange3, 'http://www.google.com', '','',' hyperlink text to display'); The output will be produced but overwriting everything in $MyRange3 and displays only the hyperlink. I would like the email address (hyperlink) to appear at the end of $MyRange3 text. example output Code: [Select] All right reserved [u]hyperlink text to display[/u] anyone can shed some light on this. Good evening, I hope some of you can bring me some hope to solve this problem. My client wants to create pdf files and let the user download it. He want's to design one word file and then import it to the application. After that the portal users can request it, which means that the application should take the word file, search and replace some keywords and then create the pdf file for download purposes. I see fpdf but this class only create pdf's. We can not convert from word or even search and replace in one pdf file. There is any solution that i can use bear in mind that our application is located in external servers? Looking forward for your help. Regards, HS Hello Guys, I need some help here.. I want to implement a Bad word filter and not quite sure how to do it.. I am grabbing the following vars from the text fields $ad_title = filter_var($_POST['ad_title'], FILTER_SANITIZE_STRING,FILTER_FLAG_NO_ENCODE_QUOTES); $ad_body = filter_var($_POST['description'], FILTER_SANITIZE_STRING,FILTER_FLAG_NO_ENCODE_QUOTES); Then its inserted into the db. I would like to run it through this function first.. Code: [Select] FUNCTION BadWordFilter(&$text, $replace){ // fill this array with the bad words you want to filter and their replacements $bads = ARRAY ( ARRAY("butt","b***"), ARRAY("poop","p***"), ARRAY("crap","c***") ); IF($replace==1) { //we are replacing $remember = $text; FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word $text = EREGI_REPLACE($bads[$i][0],$bads[$i][1],$text); //replace it } IF($remember!=$text) RETURN 1; //if there are any changes, return 1 } ELSE { //we are just checking FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word IF(EREGI($bads[$i][0],$text)) RETURN 1; //if we find any, return 1 } } } // this will replace all bad words with their replacements. $any is 1 if it found any $any = BadWordFilter($wordsToFilter,1); I really would also like to query a table for any words that match and then use a replacement like [censored] Any help would be greatly appreciated! I want to catch the first word of a string in which the words are separated by "-" (e.g. "first-word-second-one-more"). I used this code: $string = explode('-', $string); echo $string[0]; The problem is that when the string contains only one word, it returns null I have a CMS with basic toolbar and have major issues with copying and pasting from MS Word. I have a code below that I would like to test cleaning up MS Word.... Code: [Select] <?php function word_cleanup ($str) { $pattern = "/<(\w+)>(\s| )*<\/\1>/"; $str = preg_replace($pattern, '', $str); return mb_convert_encoding($str, 'HTML-ENTITIES', 'UTF-8'); } ?>And would like to add it onClick within code below, but it doesn't seem to do anything...... Code: [Select] <?php //we will have to dynamically generate either the edit and delete buttons or //the save button here depending on numevent. if($numMain!=-1) { echo("<tr><td colspan='2' align='center'><input type='submit' id='button' name='edit' value='Save Changes' onClick=\"saveChanges('edit'); onClick=\"function('word_cleanup');\"><input type='submit' id='button' name='delete' value='Delete' onClick=\"saveChanges('delete');\"></td></tr></table></form>"); } else { echo("<tr><td colspan='2' align='center'><input type='submit' id='button' name='save' value=' Save ' onClick=\"saveChanges('save'); onClick=\"function('word_cleanup');\"></td></tr></table></form>"); } ?> Any help, tips, suggestions would be so greatly appreciated. I have a table in my php Mysql which contains some values.. Is it possible to get those values then export them to MS word with formatting? and make it like a table? Help pls. hey im tring to match words which contain double s at the end...ie. address, business, class etc...so that is so i can put a ' at the end...
class'
if (preg_match("/ss$/", $name)) { $name = $name . "'"; }any help with the regular expression would be great thank you |