PHP сократить строку до 5 слов назад и вперед от выделенных ключевых слов из массива

Мне нужно найти в больших строках каждое ключевое слово, выделив их и оставьте только пять слов до и после этого ключевого слова. Вы можете увидеть на скриншоте, я создал PHP-скрипт, который

Ссылка на изображение, которое показывает, что у меня есть и что мне нужно:
http://dawid969.webd.pl/cut.jpg

Код, который у меня есть — PHP — Я создал функциональность, чтобы выделить каждое слово, но я не могу обрезать строку (вокруг выделенных слов пять слов назад и 5 слов вперед), есть такие странные ситуации, когда каждое выделенное слово находится рядом друг с другом, тогда мы не можем вырезать Строка, мы обрезаем строку только тогда, когда разные слова между выделенными словами больше 10 слов.

Кто-нибудь есть идеи, как я могу сделать последнее замечание? — резка струны?

<?php
$sentence = "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again";

$arrayOfWords = array('explain', 'complete', 'pleasure');

echo "<b>Sentence:</b> ".$sentence;
echo '<br><br>';

echo "<b>Words to find (in array):</b> ";
print_r($arrayOfWords);

echo "<br><br>";

$look = explode(' ',$sentence);

foreach($look as $find){
for($i=0;$i<count($arrayOfWords);$i++){
$keyword = $arrayOfWords[$i];
if(stripos($find, $keyword) !== false) {
if(!isset($highlight)){
$highlight[] = $find;
} else {
if(!in_array($find,$highlight)){
$highlight[] = $find;
}
}
}
}
}

if(isset($highlight)){
foreach($highlight as $key => $replace){
$sentence = str_replace($replace,'<b>'.$replace.'</b>',$sentence);
}
}

echo "<b>Sentence formatted I have:</b> ".$sentence;

echo '<br><br>';

echo "<b>Sentence formated I need: </b> But I must <b>explain</b> to you how all this mistaken idea of denouncing <b>pleasure</b> and praising pain was born and I will give you a <b>complete</b> account of the system, and expound... ...one rejects, dislikes, or avoids <b>pleasure</b> itself, because it is pleasure,... ...not know how to pursue <b>pleasure</b> rationally encounter consequences that are...";
?>

0

Решение

Мой шаблон регулярных выражений может занять немного «глядя на», но в основном они соответствуют 5 «словам» (используя термин свободно) по обе стороны от каждого найденного ключевого слова.

Предложение сначала делится на массив подстрок, которые либо содержат, либо не содержат ключевые слова. Вызов var_export($chunks); чтобы понять, что я имею в виду.

Затем каждый элемент обрабатывается условно. Если элемент:

  • содержит ключевое слово, подбадривающее действие принято.
  • это ровно один пробел, элемент остается один.
  • не содержит ключевое слово и является первым или последним элементом, становится ...,
  • не содержит ключевое слово и встречается в середине предложения, становится ... ...,

Код: (демонстрация)

$sentence = "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again";
$arrayOfWords=['explain','complete','pleasure'];
$pattern_core=implode('|',array_map(function($v){return preg_quote($v,'/');},$arrayOfWords));  // escape regex-impacting characters and pipe together

// split the sentence on keywords with upto 5 "words" padding, retain the delimiters
$chunks=preg_split("/((?:\S+\s+){0,5}\S*(?:".$pattern_core.")\S*(?:\s+\S+){0,5})/iu",$sentence,-1,PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);

$last_chunk=sizeof($chunks)-1;
foreach($chunks as $i=>&$chunk){  // make $chunk modifiable with & symbol
$chunk=preg_replace("/{$pattern_core}/iu",'<b>$0</b>',$chunk,-1,$count);
if(!$count && $chunk!=' '){  // if contains no keyword and not a single space...
if($i==0 || $i==$last_chunk){  // single set of dots at beginning and end of sentence
$chunk='...';
}else{
$chunk='... ...';  // double set of dots in the middle of sentence
}
}
}
echo implode($chunks);

Выход:

But I must <b>explain</b> to you how all this mistaken idea of denouncing <b>pleasure</b> and praising pain was born... ...I will give you a <b>complete</b> account of the system, and... ...one rejects, dislikes, or avoids <b>pleasure</b> itself, because it is <b>pleasure</b>,... ...not know how to pursue <b>pleasure</b> rationally encounter consequences that are...
0

Другие решения

<?php
$sentence = "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again";

$arrayOfWords = array('explain', 'complete', 'pleasure');

echo "<b>Sentence:</b> ".$sentence;
echo '<br><br>';

echo "<b>Words to find (in array):</b> ";
print_r($arrayOfWords);

echo "<br><br>";

//replace this part

$look = explode(' ',$sentence);
$last_checked =0;
$i=0;
$highlight=false;
for(;$i<count($look);$i++){
foreach ($arrayOfWords as $keyword){
$find=$look[$i];
if(stripos($find, $keyword) !== false) {
$highlight =true;
if($i-$last_checked>10){
$j = ($last_checked ==0)?0:  $last_checked+ 5;
$dots=true;

for(;$j<$i -5;$j++) {
if($dots){
$look[$j]= "...";
$dots=false;
}else
$look[$j]= "";
}
}
$last_checked =$i;
}
}
}$sentence=implode(" ",$look);if(isset($highlight)){
foreach($arrayOfWords as $key => $replace){
$sentence = str_replace($replace,'<b>'.$replace.'</b>',$sentence);
}
}

echo "<b>Sentence formatted I have:</b> ".$sentence;

echo '<br><br>';

echo "<b>Sentence formated I need: </b> But I must <b>explain</b> to you how all this mistaken idea of denouncing <b>pleasure</b> and praising pain was born and I will give you a <b>complete</b> account of the system, and expound... ...one rejects, dislikes, or avoids <b>pleasure</b> itself, because it is pleasure,... ...not know how to pursue <b>pleasure</b> rationally encounter consequences that are...";
?>

Я надеюсь, что это дает вам представление, я не сосредоточился на точных цифрах.

-1

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector