indexOf and lastIndexOf in PHP?

2019-03-17 12:35发布

问题:

In Java, we can use indexOf and lastIndexOf. Since those functions don't exist in PHP, what would be the PHP equivalent of this Java code?

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

回答1:

You need the following functions to do this in PHP:

strpos Find the position of the first occurrence of a substring in a string

strrpos Find the position of the last occurrence of a substring in a string

substr Return part of a string

Here's the signature of the substr function:

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

The signature of the substring function (Java) looks a bit different:

string substring( int beginIndex, int endIndex )

substring (Java) expects the end-index as the last parameter, but substr (PHP) expects a length.

It's not hard, to get the end-index in PHP:

$sub = substr($str, $start, $end - $start);

Here is the working code

$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:

In php:

  • stripos() function is used to find the position of the first occurrence of a case-insensitive substring in a string.

  • strripos() function is used to find the position of the last occurrence of a case-insensitive substring in a string.

Sample code:

$string = 'This is a string';
$substring ='i';
$firstIndex = stripos($string, $substring);
$lastIndex = strripos($string, $substring);

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

Output: Fist index = 2 Last index = 13



回答3:

<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>