我想查找字符串中的4。只有4,而不是44或14或4444 ...php在字符串中查找字符,但單獨使用字符
我不能使用strpos
,因爲當找到4時,當找到44或找到444444時它返回0。
我應該使用什麼函數?
感謝
我想查找字符串中的4。只有4,而不是44或14或4444 ...php在字符串中查找字符,但單獨使用字符
我不能使用strpos
,因爲當找到4時,當找到44或找到444444時它返回0。
我應該使用什麼函數?
感謝
使用preg_match()
與negative lookbehind and negative lookahead:
preg_match('/((?<!4)4(?!4))/', $string, $m);
if ($m && count($m) == 2) {
// matched "only one 4"
}
我想這不僅僅是一個猜測,這是你的答案,你明白OP想要從這個問題中得到什麼。 –
@FrayneKonok,總是有機會不正確地理解OP。嗨可能更具體,但我想我已經明白他的意思了。 –
我會重申那個。如果我使用的測試字符串'$字符串=「444or4444or44or24」;'它找到'只是在最後'24' – RiggsFolly
試試這個,使用preg_match_all
$str = 'Just 44 4 test 444';
preg_match_all('!\d+!', $str, $matches);
// print_r($matches);
if (in_array("4", $matches[0])){
echo "Match found";
}
else
{
echo "Match not found";
}
我似乎無法打破這一個! UV – RiggsFolly
@miguelmas檢查此答案似乎牢不可破 – RiggsFolly
它返回零,因爲它在'0'列中找到'4' – RiggsFolly
@FrayneKonok我不是那個在猜測的人,你是 – RiggsFolly
歡迎來到SO。請看[旅遊](http://stackoverflow.com/tour)。您可能還想檢查[我可以詢問哪些主題](http://stackoverflow.com/help/on-topic)以及[如何提出一個好問題](http://stackoverflow.com/help/)如何提問)和[完美問題](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/),以及如何創建[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。發佈您嘗試過的代碼以及收到的錯誤。儘可能具體,因爲它會導致更好的答案。 –