1

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

0

2 Answers 2

2

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
)
Sign up to request clarification or add additional context in comments.

2 Comments

what does ~i means in preg_grep()?
i is for ignore case and ~ is regex delimiter here.
2

preg_grep does the trick:

$input = preg_quote('bl', '~'); // don't forget to quote input string!
$data = array('orange', 'blue', 'green', 'red', 'pink', 'brown', 'black');

$result = preg_grep('~' . $input . '~', $data);

hope this will sure work for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.