* strpos.js

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 不是false

 

php写法:

    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,常规字符串没有问题, 遇到 }" 出错

<?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

js实现php strpos函数_JavaScript