Jump to content

explode help


Kane250

Recommended Posts

Hi,

 

I'm using the following code to select a paragraph of text, and split the paragraph up into sentences, but it's far from working perfectly.

 

Every time it runs, I am getting a trailing blank entry in MySQL.  I'm also not getting the periods from the sentences.  Any idea how I can fix this?  Also, is there an easy reg exp that I could use so it will separate sentences by (. , !, and ?) and tell it to ignore multiple line endings like: ...  or ??  ?

 

//Collect data from paragraph and put into a variable
$para1content = ($_POST['finalFirstPara']);

//Separate data into sentences, spearated by (.) and put into an array
$para1exploded = (explode('.', $para1content));


foreach ($para1exploded as $content) //This iterates through the selected exploded array
{	
		$query = "INSERT INTO `para1` (`text`, `key`, `added_at`) VALUES ('$content', '$key', CURRENT_TIMESTAMP)";

	if (!mysql_query($query,$conn))
	{
		die('Error=' . mysql_error());
	}
};

 

Thanks in advance!

 

Link to comment
https://forums.phpfreaks.com/topic/152454-explode-help/
Share on other sites

array_pop

 

When you explode an array it will default the last item (given the sentences) to a black space, if you are splitting something where the option to split by is the last character. Using the above will remove that issue.

 

As for the sentence issue, I am not sure what you are trying to get at.

 

EDIT:

Incase you may have a scenario where there is no ending period, you may want to do this over array_pop

 

<?php
   foreach ($para1exploded as $content) //This iterates through the selected exploded array
   {   
       if (empty($content)) 
             continue;
       $query = "INSERT INTO `para1` (`text`, `key`, `added_at`) VALUES ('$content', '$key', CURRENT_TIMESTAMP)";
?>

 

That will prevent from anything that does not have characters from being entered into the DB.

Link to comment
https://forums.phpfreaks.com/topic/152454-explode-help/#findComment-800648
Share on other sites

Thanks guys, I actually ended up using split('[.!?] ', $variable), which worked well and also allows sentences to be types in with additional periods like this... However, in a normal sentence with just one period, it is still omitting that period.  Anyway I can have it include a period that ends a sentence, but still include them when someone types extras?

Link to comment
https://forums.phpfreaks.com/topic/152454-explode-help/#findComment-806908
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.