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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With