2014-11-14 9 views
14

В Java мы можем использовать indexOf и lastIndexOf. Поскольку эти функции не существуют в PHP, каков будет PHP-эквивалент этого Java-кода?indexOf и lastIndexOf в PHP?

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

http://php.net/manual/en/function.strstr.php – alu

+0

вы можете использовать IndexOf и LastIndexOf с помощью JavaScript, потому что они существуют в нем. – Dotnetter

+0

* «Поскольку эти функции не существуют в PHP» * - вы их обыскали? В прошлый раз, когда я проверял, PHP все еще предоставлял эту функциональность. 'indexOf' называется [' strpos() '] (http://php.net/manual/en/function.strpos.php),' lastIndexOf' имеет имя ['strrpos()'] (http: // php .net/ручной/EN/function.strrpos.php). – axiac

ответ

10

В 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

20

Вам понадобятся следующие функции, чтобы сделать это в 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) ожидает длину.

Это не трудно, чтобы get the end-index in 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
<pre> 

<?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 "4" 


//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 "2" 


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

?> 
</pre> 
Смежные вопросы