Nathan Srivi Nathan Srivi - 7 days ago 7
PHP Question

Find Keyword in array using php?

I have one keyword like this format

sample text


Also i have one array like this following format

Array
(
[0] => Canon sample printing text
[1] => Captain text
[2] => Canon EOS Kiss X4 (550D / Rebel T2i) + Double Zoom Lens Kit
[3] => Fresh sample Roasted Seaweed
[4] => Fresh sample text Seaweed
)


I want to find
sample text
keyword in this array.
My expected result

Array
(
[0] => Canon sample printing text //Sample and Text is here
[1] => Captain text //Text is here
[3] => Fresh sample Roasted Seaweed //Sample is here
[4] => Fresh sample text Seaweed //Sample text is here
)


I am already trying
strpos
but its not getting correct answer

Please advise

Answer

A simple preg_grep will do the job:

$arr = array(
    'Canon sample printing text',
    'Captain text',
    'Canon EOS Kiss X4 (550D / Rebel T2i) + Double Zoom Lens Kit',
    'Fresh sample Roasted Seaweed',
    'Fresh sample text Seaweed'
);
$matched = preg_grep('~(sample|text)~i', $arr);
print_r($matched);

OUTPUT:

Array
(
    [0] => Canon sample printing text
    [1] => Captain text
    [3] => Fresh sample Roasted Seaweed
    [4] => Fresh sample text Seaweed
)
Comments