* strpos.jsjavascript
function strpos(haystack, needle, start) { if (typeof(start)==="undefined") { start = 0; } if (!needle) { return 0; } var j = 0; for (var i = start; i < haystack.length && j < needle.length; i++) { if (haystack.charAt(i) === needle.charAt(j)) { j++; } else { j = 0; } } if (j === needle.length) { return i - needle.length; } return -1; }
找不到返回-1 不是falsephp
php寫法:java
public static function pos($haystack, $needle, $start = 0) { if (!$needle) { return 0; } $j = 0; $m = strlen($haystack); $n = strlen($needle); for ($i = $start; $i < $m && $j < $n; $i++) { if ($haystack[$i] === $needle[$j]) { $j += 1; } else { $j = 0; } } if ($j === $n) { return $i - $n; } return -1; }
這個本身實現的strpos有bug,常規字符串沒有問題, 遇到 }" 出錯dom
<?php function mystrpos($haystack, $needle, $start = 0) { if (!$needle) { return 0; } $j = 0; $m = strlen($haystack); $n = strlen($needle); for ($i = $start; $i < $m && $j < $n; $i++) { if ($haystack[$i] === $needle[$j]) { $j += 1; } else { $j = 0; } } if ($j === $n) { return $i - $n; } return -1; } $s = <<<EOF {"msg":"{"domain_id":1018,"info":{"a":1,"b":2,"c":[1,2]}}","msg_id":"1620412048055uJTJ","msg_request_id":"cb7bc4dc-44a1-4842-9053-146648a91f30","msg_action":"query_change_registrant_result","msg_timestamp":1620412048055} EOF; $idx = mystrpos($s, '"{'); var_dump($idx); // ok $idx = mystrpos($s, '}"'); var_dump($idx); // bug $idx = strpos($s, '}"'); var_dump($idx); // ok