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("-"));
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.
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)
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.
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.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With