Say I have the following 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?
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;
}
}
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;
}
foreach ($data_array as $val) {
if (strstr($val, 'dog')) {
echo $val;
}
}
您可以使用此示例:
$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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.