Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexOf and lastIndexOf in PHP?

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("-")); 
like image 888
Gaurav Avatar asked Nov 14 '14 05:11

Gaurav


People also ask

What is the difference between indexOf and lastIndexOf?

indexOf() method returns the position of the first occurrence of a specified value in a string. string. lastIndexOf() method returns the position of the last occurrence of a specified value in a string.

How do I get the last index of a string in PHP?

The strrpos() function finds the position of the last occurrence of a string inside another string. Note: The strrpos() function is case-sensitive. Related functions: strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)

What does the indexOf () method do?

The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.

What is indexOf and lastIndexOf in Javascript?

Overview. The lastIndexOf method in javascript returns the index of the last occurrence of the specified substring. Given a second argument, a number, the lastIndexOf() method returns the last occurrence of the specified substring at an index less than or equal to the number.


1 Answers

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); } 
like image 98
Alfred Bez Avatar answered Oct 02 '22 18:10

Alfred Bez