IndexOf и lastIndexOf в PHP?
В Java мы можем использовать indexOf
и lastIndexOf
. Поскольку эти функции не существуют в 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("-"));
Ответы
Ответ 1
Для этого вам понадобятся следующие функции в PHP:
strpos
Найти позицию первого вхождения подстроки в строке
strrpos
Найти позицию последнего вхождения подстроки в строке
substr
Возвращает часть строки
Вот подпись функции substr
:
string substr ( string $string , int $start [, int $length ] )
Сигнатура функции 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);
}
Ответ 2
В php:
-
stripos() используется для определения положения первого вхождения case- нечувствительная подстрока в строке.
-
strripos() используется для определения положения последнего вхождения case- нечувствительная подстрока в строке.
Пример кода:
$string = 'This is a string';
$substring ='i';
$firstIndex = stripos($string, $substring);
$lastIndex = strripos($string, $substring);
echo 'Fist index = ' . $firstIndex . ' ' . 'Last index = '. $lastIndex;
Выход: индекс Fist = 2 Последний индекс = 13
Ответ 3
<?php
// sample array
$fruits3 = [
"iron",
1,
"ascorbic",
"potassium",
"ascorbic",
2,
"2",
"1",
];
// Let 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()