在PHP中的indexOf和lastIndexOf是什么?

42

在Java中,我们可以使用indexOflastIndexOf。由于PHP中不存在这些函数,那么在PHP中,什么是与此Java代码等效的方法?

if(req_type.equals("RMT"))
    pt_password = message.substring(message.indexOf("-")+1);
else 
    pt_password = message.substring(message.indexOf("-")+1,message.lastIndexOf("-"));

2
http://php.net/manual/en/function.strstr.php - alu
你可以使用 JavaScript 中的 IndexOf 和 LastIndexOf,因为它们已经存在于该语言中。 - Dotnetter
1
"由于这些函数在PHP中不存在" - 你有搜索过吗?上次我检查时,PHP仍然提供了这些功能。indexOf被命名为strpos()lastIndexOf被命名为strrpos() - axiac
4个回答

63

在 PHP 中,您需要以下函数来完成此操作:

strpos 查找字符串中第一次出现子字符串的位置

strrpos 查找字符串中最后一次出现子字符串的位置

substr 返回字符串的一部分

下面是 substr 函数的签名:

string substr ( string $string , int $start [, int $length ] )
< p > substring 函数的签名(Java)看起来有些不同:

string substring( int beginIndex, int endIndex )
substring(Java)期望最后一个参数为结束索引,而substr(PHP)期望长度作为参数。
在PHP中,很容易通过结束索引获取所需的长度:请参考此处
$sub = substr($str, $start, $end - $start);

这是可运行的代码。

$start = strpos($message, '-') + 1;
if ($req_type === 'RMT') {
    $pt_password = substr($message, $start);
}
else {
    $end = strrpos($message, '-');
    $pt_password = substr($message, $start, $end - $start);
}

22
在 PHP 中:
- stripos() 函数用于在字符串中查找第一个不区分大小写的子字符串出现的位置。 - strripos() 函数用于在字符串中查找最后一个不区分大小写的子字符串出现的位置。
示例代码:
$string = 'This is a string';
$substring ='i';
$firstIndex = stripos($string, $substring);
$lastIndex = strripos($string, $substring);

echo 'Fist index = ' . $firstIndex . ' ' . 'Last index = '. $lastIndex;

输出: 第一个索引 = 2 最后一个索引 = 13


5
<?php
// sample array
$fruits3 = [
    "iron",
    1,
    "ascorbic",
    "potassium",
    "ascorbic",
    2,
    "2",
    "1",
];

// Let's say we are looking for the item "ascorbic", in the above array

//a PHP function matching indexOf() from JS
echo(array_search("ascorbic", $fruits3, true)); //returns "2"

// a PHP function matching lastIndexOf() from JS world
function lastIndexOf($needle, $arr)
{
    return array_search($needle, array_reverse($arr, true), true);
}

echo(lastIndexOf("ascorbic", $fruits3)); //returns "4"

// so these (above) are the two ways to run a function similar to indexOf and lastIndexOf()

-2

这是最好的方法,非常简单。

$msg = "Hello this is a string";
$first_index_of_i = stripos($msg,'i');
$last_index_of_i = strripos($msg, 'i');

echo "First i : " . $first_index_of_i . PHP_EOL ."Last i : " . $last_index_of_i;

1
请始终将您的答案放在上下文中,而不仅仅是粘贴代码。有关更多详细信息,请参见此处 - gehbiszumeis
它究竟有什么使它成为“最好”的特点? - ggorlen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接