Chaturrin
Chaturrin

Reputation: 21

Regular expression to search word in text and not as part of a string (preg_match_all)

I hope anyone can help me with this question.

What I'm looking for is to search a string for a word

$text = 'is Apple, name testintapple test APPLE name test';
preg_match_all('/apple/i', $text, $output_array);

Return

array(
0   =>  Apple
1   =>  apple
2   =>  APPLE
)

I would like this to just return:

array(
0   =>  Apple
1   =>  APPLE
)

Upvotes: 2

Views: 44

Answers (1)

Gerard de Visser
Gerard de Visser

Reputation: 8050

What you need is:

preg_match_all('/\bapple\b/i', $text, $output_array);

The \b is a word boundary. So it will only match if apple is used as a word an not a part of a bigger string.

Upvotes: 4

Related Questions