首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用php在数组中查找关键字?

使用php在数组中查找关键字?
EN

Stack Overflow用户
提问于 2013-10-23 08:53:08
回答 2查看 1.7K关注 0票数 1

我有一个像这种格式的关键字

sample text

另外,我有一个类似于以下格式的数组

代码语言:javascript
复制
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
)

我想在这个数组中找到sample text关键字。我的预期结果

代码语言:javascript
复制
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
    )

我已经在尝试strpos了,但它没有得到正确的答案

请指教

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-10-23 09:03:12

一个简单的preg_grep将完成以下工作:

代码语言:javascript
复制
$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);

输出:

代码语言:javascript
复制
Array
(
    [0] => Canon sample printing text
    [1] => Captain text
    [3] => Fresh sample Roasted Seaweed
    [4] => Fresh sample text Seaweed
)
票数 2
EN

Stack Overflow用户

发布于 2013-10-23 09:03:05

grep的诀窍是:

代码语言:javascript
复制
$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);

希望这对你一定有用。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19537145

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档