36

在 Java 中,我们可以使用indexOflastIndexOf。由于这些函数在 PHP 中不存在,那么这个 Java 代码的 PHP 等价物是什么?

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

4 回答 4

55

您需要以下函数在 PHP 中执行此操作:

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

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

substr返回字符串的一部分

这是substr函数的签名:

string substr ( string $string , int $start [, int $length ] )

函数 (Java)的签名substring看起来有点不同:

string substring( int beginIndex, int endIndex )

substring(Java) 期望 end-index 作为最后一个参数,但substr(PHP) 期望一个长度。

在 PHP 中通过 end-index 获得所需的长度并不难:

$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);
}
于 2016-04-18T10:06:16.257 回答
20

在 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

于 2015-09-03T04:57:04.657 回答
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()
于 2016-06-03T18:36:35.447 回答
0

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

$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;
于 2019-12-11T12:58:41.600 回答