Grab x number of words before and after a given keyword?
问题 How can I go about grabbing [x] number of words before and after a given keyword in a string in PHP? I am trying to tokenize results from a mysql query tailored to the keyword as a snippet. 回答1: $string = 'This is a test string to see how to grab words from an arbitrary sentence. It\'s a little hacky (as you can see from the results) - but generally speaking, it works.'; echo $string,'<br />'; function getWords($string,$word,$before=0,$after=0) { $stringWords = str_word_count($string,1);