I have some sentences. I have to choose the sentences that consist of more than 6 words. and then they will be inserted to database.
<?php
require_once 'conf/conf.php';
$text = " Poetry. Do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories. ";
$sentences = explode(".", $text);
foreach ($sentences as $sentence) {
if (count(preg_split('/\s+/', $sentence)) > 6) {
$save = $sentence. ".";
$sql = mysql_query("INSERT INTO tb_name VALUES('','$save')");
}
}
?>
The result is only the second sentence that inserted in database => 'Do you read poetry while flying? Many people find it relaxing to read on long flights'. whereas the third sentence also should be inserted. please help me, thank you : )
Here is the solution you're looking for. You cannot add multiple rows since your ID value is left unspecified and it is the key into the table. Since you want to add the sentences to the same row, you need to execute one query.
$text = " Poetry. Do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories. ";
$sentences = explode(".", $text); $save = array();
foreach ($sentences as $sentence) {
if (count(preg_split('/\s+/', $sentence)) > 6) {
$save[] = $sentence. ".";
}
}
if( count( $save) > 0) {
$sql = mysql_query("INSERT INTO tb_name VALUES('','" . implode( ' ', $save) . "')");
}
Now, both sentences will be inserted into the same row in the database, separated by a space. You can change what they're separated by if you modify the first parameter to implode().
The query that gets generated is this:
INSERT INTO tb_name VALUES('',' Do you read poetry while flying? Many people find it relaxing to read on long flights. Poetry can be divided into several genres, or categories.')
Replace:
$sentences = explode(".", $text);
with this:
$newSentences = array();
$sentences = preg_split("/(\.|\?|\!)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$odd = false;
foreach($sentences as $sentence) {
$sentence = trim($sentence);
if($sentence != '') {
if(!$odd) {
$newSentences[] = $sentence;
} else {
$newSentences[count($newSentences) - 1] .= $sentence;
}
$odd = !$odd;
}
}
It separates sentences ending in with . or ? or !. The foreach just reassembles the sentences.
Example here: http://codepad.org/kk3PsVGP
Related
I've got a script that I needed to change since the data which is going to be inserted into the db got too big to do it at once. So I created a loop, that splits up the array in blocks of 6000 rows and then inserts it.
I don't know exactly if the data is to big for the server to process at once or if it's too big to upload, but atm I got both steps split up in these 6000s blocks.
Code:
for ($j = 0; $j <= ceil($alength / 6000); $j++){
$array = array_slice($arraysource, $j * 6000, 5999);
$sql = "INSERT INTO Ranking (rank, name, score, kd, wins, kills, deaths, shots, time, spree) VALUES ";
foreach($array as $a=>$value){
//transforming code for array
$ra = $array[$a][0];
$na = str_replace(",", ",", $array[$a][1]);
$na = str_replace("\", "\\\\", $na);
$na = str_replace("'", "\'", $na);
$sc = $array[$a][2];
$kd = $array[$a][3];
$wi = $array[$a][4];
$ki = $array[$a][5];
$de = $array[$a][6];
$sh = $array[$a][7];
$ti = $array[$a][8];
$sp = $array[$a][9];
$sql .= "('$ra',' $na ','$sc','$kd','$wi','$ki','$de','$sh','$ti','$sp'),";
}
$sql = substr($sql, 0, -1);
$conn->query($sql);
}
$conn->close();
Right now it only inserts the first 5999 rows, but not more as if it only executed the loop once. No error messages..
Don't know if this'll necessarily help, but what about using array_chunk, array_walk, and checking error codes (if any)? Something like this:
function create_query(&$value, $key) {
//returns query statements; destructive though.
$value[1] = str_replace(",", ",", $value[1]);
$value[1] = str_replace("\", "\\\\", $value[1]);
$value[1] = str_replace("'", "\'", $value[1]);
$queryvalues = implode("','",$value);
$value = "INSERT INTO Ranking (rank, name, score, kd, wins, kills, deaths, shots, time, spree) VALUES ('".$queryvalues."');";
}
$array = array_chunk($arraysource, 6000);
foreach($array as $key=>$value){
array_walk($value,'create_query');
if (!$conn->query($value)) {
printf("Errorcode: %d\n", $conn->errno);
}
}
$conn->close();
Secondly, have you considered using mysqli::multi_query? It'll do more queries at once, but you'll have to check the max allowed packet size (max_allowed_packet).
Another tip would be to check out the response from the query, which your code doesn't include.
Thanks for the tips but I figured it out. Didn't think about this ^^
it was the first line after the for loop that i didnt include in my question:
array_unshift($array[$a], $a + 1);
this adds an additional value infront of each user, the "rank". But the numbers would repeat after one loop finishes and it can't import users with the same rank.
now it works:
array_unshift($array[$a], $a + 1 + $j * 5999);
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?
I wonder if anyone can help with a little problem I can't seem to fix - my
head is going round in circles at the moment...
Ok I have a .txt file with numerous lines of info - I am trying to match keywords
with those lines and display a certain number of the matching lines.
I put together this bit of script and whilst it works it only matches a line if the
words are in the same order as the search words.
At the moment as an example:
Search words:
red hat
Lines in .txt file:
this is my red hat
my hat is red
this hat is green
this is a red scarf
your red hat is nice
As the script is at the moment it will match and display lines 1, 5
However I would like it to match and display lines 1, 2, 5
Any order but all words must be present to match.
I have looked through loads of postings here and elsewhere and I understand that
what is needed is to explode the string and then search for each word in a loop but
I cannot get that to work, despite trying a few different ways as it just returns the
same line numerous times.
Any help would be appreciated before I lose what hair I have left :-)
Here is the code I have working at present - the search variable is already
set:
<?php
rawurldecode($search);
$search = preg_replace('/[^a-z0-9\s]|\n|\r/',' ',$search);
$search = strtolower($search);
$search = trim($search);
$lines = file('mytextfile.txt') or die("Can't open file");
shuffle($lines);
$counter = 0;
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
if(strpos($line, $search) !== false AND $counter <= 4)
{
$found = true;
$line = '<img src=""> '.$line.'<br>';
echo $line;
$counter = $counter + 1;
}
}
// If the text was not found, show a message
if(!$found)
{
echo $noresultsmessage;
}
?>
Thanks in advance for any help - still learning :-)
Here's my code:
$searchTerms = explode(' ', $search);
$searchCount = count($searchTerms);
foreach($lines as $line)
{
if ($counter <= 4) {
$matchCount = 0;
foreach ($searchTerms as $searchWord) {
if (strpos($line, $searchWord) !== false ) {
$matchCount +=1;
} else {
//break out of foreach as no need to check the rest of the words if one wasn't found
continue;
}
}
if ($matchCount == $searchCount) {
$found = true;
$line = '<img src=""> '.$line.'<br>';
echo $line;
$counter = $counter + 1;
}
}
}
I know this is kinda weird, but I need this to complete my task.
I want to move the first two words to the two words thereafter, example is in my (error) code :
<?
$sentence = "zero one two three four five six seven eight";
$sentence2 = explode (" ",$sentence);
$total = count($sentence2);
for ($i = 4; $i < $total; ++$i) {
$result = $sentence2[2]." ".$sentence2[3]." ".$sentence2[0]." ".$sentence2[1]." ".$sentence2[$i];
}
echo "Original sentence : ".$sentence;
echo "<br>Result : ".$result;
?>
but the result from that code is not what i want, the result is
two three zero one eight
i want the result :
two three zero one four five six seven eight
can you help me make a better code?
Each time the code inside your loop runs, the $result variable receives a new value.
You should only append words at the end of the sequence to it.
So, replace you for loop by this:
$result = $sentence2[2]." ".$sentence2[3]." ".$sentence2[0]." ".$sentence2[1];
for ($i = 4; $i < $total; ++$i) {
$result .= " ".$sentence2[$i];
}
You can also use array_splice for this case
$sentence = "zero one two three four five six seven eight";
$words = explode(" ",$sentence,3);
$base = explode(" ",$words[2]);
array_splice($base,2,0,array($words[0],$words[1]));
echo implode(" ",$base);
or one line solution,:-)
echo preg_replace('#^(\w+\s+)(\w+\s+)(\w+\s+)(\w+\s+)#','$3$4$1$2',$sentence);
The problem is that you overwrite the result all the time.
So when it steps through your for-loop the first time the string will be
two three zero one five
The second time it will be
two three zero one six
etc.
But you will only see it ending by eight because you output the string only at the end.
You should store your new string in a variable and append your next number to that.
It should read something like;
<?
$sentence = "zero one two three four five six seven eight";
$sentence2 = explode (" ",$sentence);
$total = count($sentence2);
$result = $sentence2[2]." ".$sentence2[3]." ".$sentence2[0]." ".$sentence2[1]." ";
for ($i = 4; $i < $total; ++$i) {
$result = $result." ".$sentence2[$i];
}
echo "Original sentence : ".$sentence;
echo "<br>Result : ".$result;
?>
This does the trick nicely.
$sentence = "zero one two three four five six seven eight";
$sentenceParts = explode (" ",$sentence);
$itemCount = count($sentenceParts);
$result = $sentenceParts[2]." ".$sentenceParts[3]." ";
for($i = 0; $i < $itemCount; $i++) {
if($i != 2 && $i !=3) {
$result .= $sentenceParts[$i]." ";
}
}
echo $result;
If I want to display the text as follows in example, how can it be done?
$tmp=mysql_query("SELECT ... FROM ....");
$total=mysql_num_rows($tmp);
$tekst1='Your total number of friends are: '.$total.'. Your friends are: ';
while($p=mysql_fetch_array($tmp)) {
$tekst2=$p['friend'].", ";
}
$text_complete=$tekst1.$tekst2;
echo $text_complete;
$text_complete should look like: "Your total number of friends are: 3. Your friends are: John, Mike, Michael". But, using this code above I get "Your total number of friends are: 3. Your friends are: John,"
How can I combine both texts, the one obtained from the loop and the one which is fixed?
I think you shoul do like this:
$tmp=mysql_query("SELECT ... FROM ....");
$total=mysql_num_rows($tmp);
$tekst1='Your total number of friends are: '.$total.'. Your friends are: ';
$friends = array();
while($p = mysql_fetch_array($tmp)) {
$friends[] = $p['friend'];
}
$tekst2= implode(', ', $friends);
$text_complete=$tekst1.$tekst2;
echo $text_complete;
otherwise you overwrite the variable each time!
EDIT - i corrected the code to use implode as in Xaerxess answer. Previousli i just concatenated and use a substr to remove trailing comma and space
You can use:
$tekst2 .= $p['friend'].", ";
To add to the variable (rather than overwriting it. Then remove the trailing comma:
$text_complete=$tekst1. rtrim( $tekst2, "," );
$tekst2 = new Array();
while($p=mysql_fetch_array($tmp)) {
$tekst2[] = $p['friend'];
}
$text_complete = $tekst1 . implode(', ',$tekst2);
But better would be to use GROUP_CONCAT in sql
$tmp=mysql_query("SELECT ... FROM ....");
$total=mysql_num_rows($tmp);
$tekst = '';
$tekst='Your total number of friends are: '.$total.'. Your friends are: ';
while($p=mysql_fetch_array($tmp)) {
$tekst.=$p['friend'].", ";
}
echo $tekst;
$tmp=mysql_query("SELECT ... FROM ....");
$total=mysql_num_rows($tmp);
$tekst1='Your total number of friends are: '.$total.'. Your friends are: ';
while($p=mysql_fetch_array($tmp))
{
$tekst1 .= $p['friend'].", "; // add friend names from MySQL result.
}
$tekst1 = substr($tekst2, 0, -2);//Remove comma.
echo $tekst1; // Outputs the wanted string
Use PHP implode / join funciton, so there isn't any trailing comma at the end. In this case:
$fiends = array();
while($p = mysql_fetch_array($tmp)) {
$friends[] = $p['friend'];
}
implode(', ', $friends);
EDIT: I basically doubled Billy Moon answer. What's more don't use mysql_* functions - they're deprecated not recommended - see comments below.