indexOf and lastIndexOf in PHP?

Gaurav picture Gaurav · Nov 14, 2014 · Viewed 103.4k times · Source

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("-"));

Answer

Alfred Bez picture Alfred Bez · Apr 18, 2016

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 desired length by 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);
}