PHP:如何检查ANY是否位于字符串中?

时间:2014-07-03 23:39:22

标签: php strpos

我试图查看是否有任何项目列表位于PHP字符串中。我知道如何使用strpos来测试一个项目:

if (strpos($string, 'abc') !== FALSE) {

但是,我如何测试,例如,是否' abc'或者' def'出现在$ string?

3 个答案:

答案 0 :(得分:1)

<?php

$string=" fish abc cat";

if (preg_match("/abc|def/", $string) === 1){
echo 'match';
}
如果在字符串

中找到abc或def,

将回显匹配

答案 1 :(得分:0)

不使用preg_match(),您无法真正做到这一点。如果您有某种分隔符,可以将其转换为数组:

$string = 'I have abc and jkl and xyz.';
$string_array = explode(' ', $string);
$needed_array = array('abc', 'jkl', 'xyz');

$found = false;
foreach($needed_array as $need){
    if( in_array($need, $string_array) ){
        $found = true;
        break;
    }
}

答案 2 :(得分:0)

尝试将所有搜索字符串存储到数组中,然后循环搜索要搜索的字符串。

$items = array('abcs', 'def');

for($i=0;$i<count($items);$i++) {
    if(strpos($string, $items[$i]) !== FALSE) {

    }
 }
相关问题