我一直在尝试将第二次出现的字符替换为某个字符
例如:Hey, I'm trying something With PHP, Is it Working?
我需要得到第二个逗号的位置,我尝试过使用strpos
,但没有成功,因为它定义了查找字符串的第一个出现,所以我得到了Position: 3
,有人知道解决方案吗?
strpos
函数接受可选的第三个参数,该参数是开始搜索目标字符串的偏移量。在这种情况下,您可以将一个调用传递给strpos
,它会查找逗号的第一个索引,并递增一,以查找第二个逗号。
$input = "Hey, I'm trying something With PHP, Is it Working?";
echo strpos($input, ",", strpos($input, ",") + 1); // prints 34
为了完整性/趣味性,我们也可以在这里使用基于regex子字符串的方法,并将子字符串匹配到第二个逗号:
$input = "Hey, I'm trying something With PHP, Is it Working?";
preg_match("/^[^,]*,[^,]*,/", $input, $matches);
echo strlen($matches[0]) - 1; // also prints 34
我知道这个问题已经得到了回答,但找到最后一个问题的更通用的解决方案是使用strrpos
。
strrpos
接受第三个可以为负的参数(与strpos相反(。如果为负数,则从右到左执行搜索,跳过干草堆的最后一个偏移字节并搜索针的第一次出现。
$foo = "0123456789a123456789b123456789c";
// Looking for '7' right to left from the 5th byte from the end
var_dump(strrpos($foo, '7', -5));