我一直在尝试寻找一种方法来查找另一个字符串中的字符串,并使用 PHP 返回找到它的位置,但不使用 strpos
,因为这将帮助我学习编程而无需过多依赖本机函数。
我该怎么做?
我不认为依赖本机函数有什么问题,但如果你只是想弄清楚像strpos
这样的东西如何在幕后工作,这里有一个非常基本的例子,只使用语言结构:
function my_strpos ($haystack, $needle, $offset = 0) {
// for loop with indexes for both strings, up to the length of $haystack
for ($h_index=$offset, $n_index=0; isset($haystack[$h_index]); $h_index++, $n_index++) {
if ($haystack[$h_index] == $needle[$n_index]) { // *CHARACTERS MATCH*
if (!isset($start_pos)) $start_pos = $h_index; // set start_pos if not set
if (!isset($needle[$n_index + 1])) return $start_pos; // all characters match
} else { // *CHARACTERS DON'T MATCH*
$n_index = -1; // reset $needle index
unset($start_pos); // unset match start pos.
}
}
// all charactes of $haystack iterated without matching $needle
return false;
}
这显然是一个朴素的实现,它不检查有效的输入或处理错误,但希望它将演示一种在另一个字符串中查找一个字符串的可能方法。
如果你真的想知道strpos
是如何在幕后工作的,这里有一篇关于如何理解PHP源代码的很棒的(虽然有点过时的)文章,恰好以strpos
为例。
你可以在这里使用 strstr,文档在这里
<?php
$haystack = "Hello my dear friend";
$needle = "friend";
// Returns false if needle is not inside haystack
strstr($haystack, $needle);
?>