Fatih Toprak
Fatih Toprak

Reputation: 1007

How can I extract the word before and after a specific keyword in a string?

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

Answers (1)

Rizier123
Rizier123

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

Related Questions