Say I have the f开发者_JAVA技巧ollowing array of strings:
$data_array = array("the dog is hairy", "cats like treats", "my mouse is tired");
I want to write a function that will extract an element from the array based on whether it contains another string.
For example, if the array element contains the string "dog" i want to return the string "the dog is hairy" for use elsewhere.
I tried using a foreach loop but it didn't work:
foreach ($data_array as $sentence){
if (stripos($sentence, "dog")){
echo $sentence;
}
}
What is the best way to go about this?
If you want to use stripos this is the code:
$data_array = array("the dog is hairy", "cats like treats", "my mouse is tired");
foreach($data_array as $value)
{
if (stripos($value, 'dog') !== FALSE)
echo $value;
}
It works fine for me.
http://sandbox.phpcode.eu/g/064bf
<?php
$data_array = array("the dog is hairy", "cats like treats", "my mouse is tired");
foreach($data_array as $data){
if (false !== stripos($data, "dog")){
echo $data;
}
}
foreach ($data_array as $val) {
if (strstr($val, 'dog')) {
echo $val;
}
}
You can use this example:
$f_array = preg_grep('/dog/i', $data_array);
You could also use preg_grep()
:
$found_array = preg_grep( '/dog/i', $data_array );
Edit: Added /i
switch for case-insensitive matching.
精彩评论