indexOf and lastIndexOf in PHP?

后端 未结 4 2076
孤独总比滥情好
孤独总比滥情好 2021-02-05 01:38

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?

<         


        
4条回答
  •  别跟我提以往
    2021-02-05 01:58

    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);
    }
    

提交回复
热议问题