2012-08-07 165 views
0

如何檢查字符串中是否有特定的工作?比方說,我有這樣的查找字符串中的字PHP

錯誤=名稱&通&電子郵件

所以我要檢查,如果名字,傳遞和/或電子郵件是在字符串中的字符串。我需要的答案是布爾值,所以我可以在那裏做一些東西。

+1

http://php.net/manual/en/function.strpos.php – xdazz 2012-08-07 07:04:11

+0

看起來像URL片段可疑。 – 2012-08-07 07:08:52

回答

1
if (stristr($string, $string_im_looking_for)){ 
    echo 'Yep!'; 
} 
0

您可以先爆炸字符串。像這樣的東西;

$arrayOfWords = explode('&', $yourString); 

然後你循環訪問數組並檢查isset。

1

使用strstr()

​​
2
<?php 
$mystring = 'wrong=name&pass&email'; 
$findme = 'name'; 
$pos = strpos($mystring, $findme); 


if ($pos === false) { 
echo "The string '$findme' was not found in the string '$mystring'"; 
} else { 
echo "The string '$findme' was found in the string '$mystring'"; 
echo " and exists at position $pos"; 
} 
?> 
0

從你的例子看起來好像你真正想要做的是分析查詢字符串,例如與parse_str

parse_str($string, $result); 
if(isset($result['name'])) 
    // Do something 

然而,如果字符串可能是畸形等,我會建議使用strpos,作爲不同於strstr和其他人並不需要創建一個新的字符串。

// Note the `!==` - strpos may return `0`, meaning the word is there at 
// the 0th position, however `0 == false` so the `if` statement would fail 
// otherwise. 
if(strpos($string, 'email') !== false) 
    // Do something