How to search in the string of words, and then pull out the words that surround it? For example, from the sentence above I find the word "search", and then I need to write the words "implement" and "in" .. I assume that you can break the string into words in an array, and then find the right one in the array and take the next and previous but it seems to me not rational.

    2 answers 2

    Did you mean it?

    <?php $sentence = 'Как осуществить поиск в строке слова, а затем выдернуть слова, которые его окружают?'; $arr=preg_split('/\s+поиск\s+/',$sentence); $before=explode(' ',$arr[0]); $after=explode(' ',$arr[1]); print_r($before); print_r($after); 

    http://ideone.com/KIYQES

    (restrictions - separator single space, I didn’t want to do the preg_split a second time)

      And why is this not rational?

       $sentence = 'Как осуществить поиск в строке слова, а затем выдернуть слова, которые его окружают?'; $words = preg_split('/\W+/u', $sentence); $idx = array_search('поиск', $words, true); if($idx !== FALSE) { /* нашли, берём соседей */ }