如何在字符串中的特定关键字之前和之后提取单词?

问题描述:

I was wondering what the best way is to get the word before and after a specific keyword from a string?

Example:

$e = "Kuru Kavrulmuş soya Fasulye: 100 gram, ortalamadır";
$_GET['word'] = 'soya';

I would like to then echo out Kavrulmuş and Fasulye.

My dynamic snippet is (for getting string)

if ( stripos($e, $_GET['word']) !== false) {
    echo '<div class="yellow">'. highlight($e,$_GET['word']) . '</div>';
}

Any ideas?

我想知道从字符串中获取特定关键字之前和之后的最佳方法是什么? p>

示例: p>

  $ e =“KuruKavrulmuşsoyaFasulye:100克,ortalamadır”; 
 $ _GET ['word'] =  'soya'; 
  code>  pre> 
 
 

我想回复Kavrulmuş code>和 Fasulye code>。 p>

我的动态片段是(用于获取字符串) p>

  if(stripos($ e,$ _GET ['word'])!== false)  {
 echo'&lt; div class =“yellow”&gt;'。 突出显示($ e,$ _ GET ['word'])。  '&lt; / div&gt;'; 
} 
  code>  pre> 
 
 

有什么想法? p> div>

You can use a simple regex with preg_match() to match the word before and after your keyword, e.g.

$str = "Kuru Kavrulmuş soya Fasulye: 100 gram, ortalamadır"; 
$_GET['word'] = 'soya';

preg_match("/(\w+) " . $_GET['word'] . " (\w+)/mu", $str, $matches);

print_r($matches);

output:

Array
(
    [0] => Kavrulmuş soya Fasulye
    [1] => Kavrulmuş
    [2] => Fasulye
)

The regex simply explained is to use \w for word characters([a-zA-Z0-9_]) with a quantifier + to match 1 or more times. So you can capture the word before and after your keyword.