Reputation: 1007
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?
Upvotes: 1
Views: 2387
Reputation: 59701
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.
Upvotes: 4