Skip to content

Instantly share code, notes, and snippets.

@NinnaP
Created February 16, 2017 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NinnaP/00962f80260d81f321c10361da431b5c to your computer and use it in GitHub Desktop.
Save NinnaP/00962f80260d81f321c10361da431b5c to your computer and use it in GitHub Desktop.
Sentence Extractor
<?php
$text = trim(fgets(STDIN));
$text = urldecode($text);
$word = trim(fgets(STDIN));
$word = urldecode($word);
$text = preg_replace('/[a-zA-Z\s],[.?!]/', '', $text);
$text = iconv('UTF-8', 'ISO-8859-1//IGNORE', $text);
$text = preg_split('/([.?!])/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$sentences = array();
for ($i=0, $n=count($text)-1; $i<$n; $i+=2) {
$sentences[] = $text[$i].$text[$i+1];
}
if ($text[$n] != '') {
$sentences[] = $text[$n];
}
$word = '/\s+'.$word .'\s*.*[.?!]/';
$result = array();
for($i=0;$i<count($sentences);$i++) {
if ((substr($sentences[$i], -1) == '.')||(substr($sentences[$i], -1) == '!')||(substr($sentences[$i], -1) == '?')) {
if (preg_match($word, $sentences[$i])) {
$result[] = trim($sentences[$i]);
}
}
}
foreach ($result as $value) {
echo $value ."\n";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment