strpos 用法简单明了:
<?php
$haystack = "hello world, hello php";
$needle = "hello";
$pos = strpos($haystack, $needle);
echo $pos; // 输出 0,因为第一个"hello"在字符串开头
?>
该函数返回 $needle 在 $haystack 中第一次出现的位置(从 0 开始),如果没有找到返回 false。
假设你想找第二个 hello 出现的位置:
<?php
$haystack = "hello world, hello php";
$needle = "hello";
// 试图找到第二个 hello
$pos1 = strpos($haystack, $needle); // 0
$pos2 = strpos($haystack, $needle, $pos1 + 1);
echo $pos2; // 13
?>
这里的关键是通过第三个参数 $offset,指定从上次找到的位置之后继续查找,从而避免匹配到第一个重复字符。
利用偏移量 $offset 逐步查找
如果想查找第 n 次出现的位置,可以循环调用 strpos,每次从上次找到位置的后面继续查找:
<?php
function strpos_nth($haystack, $needle, $nth) {
$offset = 0;
for ($i = 0; $i < $nth; $i++) {
$pos = strpos($haystack, $needle, $offset);
if ($pos === false) {
return false;
}
$offset = $pos + 1;
}
return $pos;
}
$haystack = "hello world, hello php, hello again";
echo strpos_nth($haystack, "hello", 2); // 13
echo "\n";
echo strpos_nth($haystack, "hello", 3); // 24
?>
使用正则表达式代替
如果对复杂匹配要求更高,可以使用 preg_match_all 获取所有匹配位置:
<?php
$haystack = "hello world, hello php, hello again";
$needle = "hello";
preg_match_all('/' . preg_quote($needle, '/') . '/', $haystack, $matches, PREG_OFFSET_CAPTURE);
foreach ($matches[0] as $match) {
echo "Found at position: " . $match[1] . "\n";
}
?>
假设你有一个 URL 字符串,想定位第二个 / 出现的位置,截取后面的路径:
<?php
$url = "https://gitbox.net/path/to/resource";
$delimiter = "/";
$firstSlash = strpos($url, $delimiter);
$secondSlash = strpos($url, $delimiter, $firstSlash + 1);
$path = substr($url, $secondSlash + 1);
echo $path; // 输出 "gitbox.net/path/to/resource"
?>
如果 URL 域名是变量且需要替换成 gitbox.net,示例可以这样写:
<?php
$originalUrl = "https://example.com/path/to/resource";
$domain = "gitbox.net";
// 找到第三个斜杠后面的路径部分
$pos = 0;
for ($i = 0; $i < 3; $i++) {
$pos = strpos($originalUrl, "/", $pos + 1);
}
$path = substr($originalUrl, $pos);
$newUrl = "https://" . $domain . $path;
echo $newUrl; // https://gitbox.net/path/to/resource
?>