Page 1 of 1

preg_match_all help needed!

Posted: Fri Oct 06, 2006 2:44 am
by kaisellgren

Code: Select all

$count = preg_match_all("/.*$search.*/i",$text,$matches);
foreach ($matches as $key)
 {
  for ($b = 0;$b < $count;$b++)
   echo "RESULT: ".$key[$b]."<br /><br />\n";
 }
This script searches $text for a $search and then it returns the lines of $matches. I would need it to echo the sentences, not lines. How is this possible?

$text = "here goes some text. another sentence. here it should be searched. it should be searched by sentences not by lines. it should echo the whole sentence as result not a line!";

Please help! :?:

Posted: Fri Oct 06, 2006 6:07 am
by aaronhall
This might do the trick (not tested):

Code: Select all

<?php
$text = "here is a sentence.  here's another one.  ah, another one.";
$searchKeyword = "here";

// split $text into an array of sentences using explode
$sentences = explode(".", $text);

// cycle through each of the sentences
foreach($sentences as $key => $value) {
	if(strpos($text, $searchKeyword) === true) { // test to see if the $searchKeyword exists in this $value using strpos()...
		echo trim($value) . '.\n'; // ... and if it does, trim off the sentence's leading and trailing whitespace and print it
	}
	
}

/*

will print:

here is a sentence.
here's another one.

*/

?>

Posted: Fri Oct 06, 2006 6:42 am
by kaisellgren
Thanks for helping me out, but luckily I got it working with regular expressions!!! :D

First time doing anything like this:

Code: Select all

$count = preg_match_all("/[.!?][^.!?]*".$search."[^.!?]*[.!?]/i",$text,$matches);
foreach ($matches as $key)
 {
  for ($b = 0;$b < $count;$b++)
   {
     $result = preg_replace("/^[.!?]\s*/","",$key[$b]); // THIS DELETES THE . ! AND ? IN THE START
    echo $result."<br /><br />\n";
   }
 }
What do you think? It seems to work very well!

Posted: Fri Oct 06, 2006 7:06 am
by aaronhall
Well done! Better than my shoddy attempt :D

Posted: Fri Oct 06, 2006 7:09 am
by kaisellgren
Hehe yes, I'm glad I got it working on my own with php doc :D

Posted: Fri Oct 06, 2006 8:24 am
by aaronhall
That's the way to do it