我想搜索一個字的字符串,如果沒有找到這個字,我想它搜索另一個字,並繼續前進,直到找到一個我有看到代碼來搜索字符串,但不繼續搜索。php搜索字符串,如果找不到字搜索另一個字
乾杯 阿什利
P.S PHP代碼是什麼,我需要
非常感謝您的幫助球員,
我會後我的WIP代碼的提示未來的感謝。
我想搜索一個字的字符串,如果沒有找到這個字,我想它搜索另一個字,並繼續前進,直到找到一個我有看到代碼來搜索字符串,但不繼續搜索。php搜索字符串,如果找不到字搜索另一個字
乾杯 阿什利
P.S PHP代碼是什麼,我需要
非常感謝您的幫助球員,
我會後我的WIP代碼的提示未來的感謝。
如果將所有值放入要搜索的數組中,則可以遍歷該數組,直到找到字符串中的一個值。
$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
。
`strpos`應該用在這裏而不是`strstr`,請參閱你鏈接到的手冊頁上的說明:) – mfonda 2011-01-24 19:40:22
這很簡單:
$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]}";
}
喜歡的東西:
$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";
}
你的意思
<?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.'
);
很高興有人來爲你的代碼這一點。通常,最好至少嘗試自己編寫代碼,並向我們提供未能幫助您以這種方式解決問題的代碼。 – 2011-01-24 19:31:27