2011-01-24 42 views
2

我想搜索一个字的字符串,如果没有找到这个字,我想它搜索另一个字,并继续前进,直到找到一个我有看到代码来搜索字符串,但不继续搜索。php搜索字符串,如果找不到字搜索另一个字

干杯 阿什利

P.S PHP代码是什么,我需要

非常感谢您的帮助球员,

我会后我的WIP代码的提示未来的感谢。

+1

很高兴有人来为你的代码这一点。通常,最好至少尝试自己编写代码,并向我们提供未能帮助您以这种方式解决问题的代码。 – 2011-01-24 19:31:27

回答

0

如果将所有值放入要搜索的数组中,则可以遍历该数组,直到找到字符串中的一个值。

$string = "I love to eat tacos."; 
$searchfor = array("brown", "lazy", "tacos"); 

foreach($searchfor as $v) { 
    if(strpos($string, $v)) { 
    //Found a word 
    echo 'Found '.$v; 
    break; 
    } 
} 

这将输出:

Found tacos 

这是使用strpos这是大小写敏感的。如果你不关心案件,你可以使用stripos

PHP: strpos

+0

`strpos`应该用在这里而不是`strstr`,请参阅你链接到的手册页上的说明:) – mfonda 2011-01-24 19:40:22

1

这很简单:

$string = "This is the string I want to search in for a third word"; 

$words = array('first', 'second', 'third'); 
$found = ''; 
foreach ($words as $word) { 
    if (stripos($string, $words) !== false) { 
     $found = $word; 
     break; 
    } 
} 
echo "This first match found was '$found'"; 

注意:使用strpos(或stripos为不区分大小写的搜索),因为它们只返回一个整数位置。其他如strstr返回字符串的一部分,这对于此目的而言是不必要的。

编辑:

或者,没有一个循环,你可以做一个单一的正则表达式:

$words = array('first', 'second', 'third'); 
$regex = '/(' . implode('|', $words) . ')/i'; 
//$regex becomes '/(first|second|third)/i' 
if (preg_match($regex, $string, $match)) { 
    echo "The first match found was {$match[0]}"; 
} 
1

喜欢的东西:

$haystack = 'PHP is popular and powerful'; 
$needles = array('Java','Perl','PHP'); 
$found = ''; 
foreach($needles as $needle) { 
     if(strpos($haystack,$needle) !== false) { 
       $found = $needle; 
       break; 
     } 
} 

if($found !== '') { 
     echo "Needle $found found in $haystack\n"; 
} else { 
     echo "No needles found\n"; 
} 

上面的代码会考虑子字符串匹配作为有效的匹配。例如,如果针是'HP',它将被发现,因为它是PHP的子字符串。

要充分匹配单词,你可以做的preg_match用作:

foreach($needles as &$needle) { 
     $needle = preg_quote($needle); 
} 

$pattern = '!\b('.implode('|',$needles).')\b!'; 

if(preg_match($pattern,$haystack,$m)) { 
     echo "Needle $m[1] found\n"; 
} else { 
     echo "No needles found\n"; 
} 

See it

0

你的意思

<?php 


function first_found(array $patterns, $string) { 
    foreach ($patterns as $pattern) { 
     if (preg_match($pattern, $string, $matches)) { 
      return $matches; 
     } 
    } 
} 

$founded = first_found(
    array(
     '/foo/', 
     '/bar/', 
     '/baz/', 
     '/qux/' 
    ), 
    ' yep, it qux.' 
);