假設我有一個整數88123401
,並且我想確定它是否包含數字序列,如1234,23456,45789或任何長度的數字以及任何數字的開始這在PHP中是否可能呢?如果是這樣的話,那麼如何才能發現?確定一個字符串是否包含數字序列
1
A
回答
2
有一些功能讓你去通過所有比較其前身每個字符的字符串。
function doesStringContainChain($str, $n_chained_expected)
{
$chained = 1;
for($i=1; $i<strlen($str); $i++)
{
if($str[$i] == ($str[$i-1] + 1))
{
$chained++;
if($chained >= $n_chained_expected)
return true;
}else{
$chained = 1;
}
}
return false;
}
doesStringContainChain("6245679",4); //true
doesStringContainChain("6245679",5); //false
+1
這幾乎就是我希望達到的!非常感謝你!! –
0
將數字視爲字符串,然後使用strpos()
進行搜索。
例子:
$mystring = '88123401';
$findme = '1234';
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The sequence '$findme' was not found in the number '$mystring'";
} else {
echo "The sequence '$findme' was found in the number '$mystring'";
echo " and exists at position $pos";
}
+0
會有更有效的方式去處理所有不同的序列嗎? '123','2345','34567'等? –
+0
你可能可以使用一個聰明的正則表達式,但我沒有足夠的資格來給出最好的答案。 – jtheman
2
使用一個循環,並使用@jtheman
$mystring = '88123401';
$findme = array(123,2345,34567);
foreach ($findme as $findspecificnum) {
$pos = strpos($mystring, $findme);
if ($pos === false) {
echo "The sequence '$findme' was not found in the number '$mystring'";
} else {
echo "The sequence '$findme' was found in the number '$mystring'";
echo " and exists at position $pos";
}
}
的答案保持它的簡單,直接的。
0
這可以幫助你:
$number = "88123401";
$splittedNumbers = str_split($number);
$continuous = false;
$matches[0] = '';
$i = 0;
do {
if ((int)(current($splittedNumbers) + 1) === (int)next($splittedNumbers)) {
if($continuous) {
$matches[$i] .= current($splittedNumbers);
}
else {
$matches[$i] .= prev($splittedNumbers) . next($splittedNumbers);
$continuous = true;
}
} else {
$continuous = false;
$matches[++$i] = '';
}
prev($splittedNumbers);
} while (!(next($splittedNumbers) === false));
print_r(array_values(array_filter($matches)));
這列出了所有在數組中的順序匹配。我們可以根據結果進一步處理。
結果:
Array
(
[0] => 1234
[1] => 01
)
相關問題
- 1. 確定是否一個字符串包含一個字
- 2. 如何確定一個字符串是否包含非字母數字字符?
- 3. 函數來確定一個字符串是否只包含另一個字符
- 4. 如何確定一個字符串是否包含另一個字符串
- 5. 確定一個字符串是否包含另一個字符串
- 6. 確定一個字符串是否包含一個子字符串
- 7. 確定一個字符串是否包含數組中的子字符串[NODEJS]
- 8. 確定子字符串是否包含一個隨機數
- 9. 確定一個字符串是否包含特定位置的子字符串
- 10. 確定一個字符串是否包含任何一組字符串
- 11. 確定一個字符串是否包含它內部的base64字符串
- 12. Bash確定變量名是否包含一個字符串
- 13. 確定字符串是否僅包含數字
- 14. 檢查一個字符串是否包含給定字符
- 15. 檢查一個字符串是否包含特定字符
- 16. 試圖確定一個字符串是否包含以逗號分隔的字符只包含數字
- 17. 確定一個字符串是否包含八度音的數字
- 18. 確定一個字符串是否只包含數字或逗號
- 19. 用戶定義函數來確定字符串是否包含子字符串
- 20. 確定字符串的索引是否包含字符
- 21. 檢查一個字符串是否包含數字和字母
- 22. 如何確定一個字符串包含字符串
- 23. AutoHotKey - 測試字符串是否包含另一個字符串
- 24. 試圖找到一個字符串是否包含字符串
- 25. Applescript:檢查一個字符串是否包含空字符串?
- 26. 檢查一個列表是否包含一個字符串
- 27. 驗證字符串數組是否包含某個字符串
- 28. 檢查一個字符串是否包含正確位置的子字符串
- 29. 找出一個字符串是否包含唯一字符
- 30. 如何確定一個字符串是否包含來自另一個字符串的字
您可以使用[正則表達式(http://php.net/book.pcre) – izk
這聽起來像一個家庭作業的問題,請你告訴我們你有什麼試過嗎? –
我曾試着看過子字符串和正則表達式,但我不確定如何去確定這個確切的問題。 –