Найдите определенное слово в строке, а затем оберните его - PullRequest
0 голосов
/ 23 января 2012

У меня есть большая строка, содержащая более 1000 слов.Что мне нужно, это найти определенное слово, а затем обернуть несколько слов вокруг него в переменную.

$in = 'This is a very long sentence, what I need is to find the word "phone" in this sentence, and after that, to wrap some words around it';

Как мне добиться этого:

$out = 'find the word "phone" in this sentence';

Итак, как выКак видите, когда я нахожу слово «телефон», я хочу развернуть его влево и вправо от этого слова.Реальный пример: когда вы делаете запрос в Google, ниже результата заголовка, вы получаете некоторый контент с веб-страницы, и запрос выделен жирным шрифтом.

Ответы [ 6 ]

5 голосов
/ 26 ноября 2013

Путь Регекса

Если вы хотите выделить определенные слова (текст поиска) в строке, выполните следующие действия.

PHP код:

 $in = 'This is a very long sentence, what I need is to find the word phone in this sentence, and after that, to wrap some words around it';
 $wordToFind  = 'phone';
 $wrap_before = '<span class="highlight_match">';
 $wrap_after  = '</span>';

 $out = preg_replace("/($wordToFind)/i", "$wrap_before$1$wrap_after", $in);

 // value of $out is now: 
 // This is a very long sentence, what I need is to find the word <span class="highlight_match">phone</span> in this sentence, and after that, to wrap some words around it

КОД CSS

Так как в этом примере обернутый текст соответствует классу span, вот обязательный пример CSS-кода

 <style type="text/css">
    .highlight_match {
        background-color: yellow;
        font-weight: bold;
    }
 </style>
4 голосов
/ 01 декабря 2014

благодаря @DaveRandom я только что улучшил код и переписал

<?php

$in = 'This is a very long sentence, what I need is to find the word phone in this sentence, and after that, to wrap some words around it';
$wordToFind = 'words';
$numWordsToWrap = 3;
echo $in;
echo "<br />";
$words = preg_split('/\s+/', $in);

$found_words    =   preg_grep("/^".$wordToFind.".*/", $words);
$found_pos      =   array_keys($found_words);
if(count($found_pos))
{
    $pos = $found_pos[0];
}

if (isset($pos)) 
{
    $start = ($pos - $numWordsToWrap > 0) ? $pos - $numWordsToWrap : 0;
    $length = (($pos + ($numWordsToWrap + 1) < count($words)) ? $pos + ($numWordsToWrap + 1) : count($words)) - $start;
    $slice = array_slice($words, $start, $length);

    $pre_start  =   ($start > 0) ? "...":"";    

    $post_end   =   ($pos + ($numWordsToWrap + 1) < count($words)) ? "...":"";

    $out = $pre_start.implode(' ', $slice).$post_end;
    echo $out;
} 
else 
    echo 'I didn\'t find it';
?>

вы все могли бы использовать повторно.

И снова благодаря DaveRandom

4 голосов
/ 23 января 2012

Вот способ сделать это.Я не говорю, что это лучший способ, но он будет работать.Вероятно, есть регулярный способ сделать это «лучше» или «лучше».

$in = 'This is a very long sentence, what I need is to find the word phone in this sentence, and after that, to wrap some words around it';
$wordToFind = 'phone';
$numWordsToWrap = 3;

$words = preg_split('/\s+/', $in);
if (($pos = array_search($wordToFind, $words)) !== FALSE) {
  $start = ($pos - $numWordsToWrap > 0) ? $pos - $numWordsToWrap : 0;
  $length = (($pos + ($numWordsToWrap + 1) < count($words)) ? $pos + ($numWordsToWrap + 1) : count($words) - 1) - $start;
  $slice = array_slice($words, $start, $length);
  $out = implode(' ', $slice);
  echo $out;
} else echo 'I didn\'t find it';
2 голосов
/ 23 января 2012
$out=preg_match('/\w+\s+\w+\s+\w+\s+\"phone\"\s+\w+\s+\w+\s+\w+/',$in,$m);
if ($out) $out=$m[0];

Если кавычки являются необязательными, и вы хотите использовать гибкость купола в отношении специальных символов, используйте

preg_match('/\w+[^\w]+\w+[^\w]+\w+[^\w]+phone[^\w]+\w+[^\w]+\w+[^\w]+\w+/',$in,$m);

и если вы хотите сопоставить отдельные слова, используйте

preg_match('/\w+[^\w]+\w+[^\w]+\w+[^\w]+\w*hon\w*[^\w]+\w+[^\w]+\w+[^\w]+\w+/',$in,$m);

для сопоставления "хон "в телефоне

2 голосов
/ 23 января 2012

Это относительно простой пример того, как вы могли бы сделать это:

<?php

   $in = "blah blah blah test blah blah blah";
   $search = "test";
   $replace = "--- test ---";

   $out = str_replace($search, $replace, $in);

?>
0 голосов
/ 23 января 2012
$in = 'This is a very long sentence, what I need is to find the word phone in this     sentence, and after that, to wrap some words around it';

$array = explode(" ", $in);

$how_much = 3;

$search_word = "phone";

foreach ($array as $index => $word) {
    if ($word == $search_word) {
        for ($index1 = 0; $index1 < ($how_much * 2) + 1; $index1++) {
            $key = $index-$how_much+$index1;
            echo $array[$key];
            echo " ";
        }
    }
}

Это простое решение.Разбейте предложение на пробелы, а затем отобразите слово + $ how_much в обоих направлениях.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...