indexOf and lastIndexOf in PHP?

indexOf and lastIndexOf in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

indexOf and lastIndexOf in PHP?

In Java, the String class provides dedicated methods like indexOf and lastIndexOf to locate substrings by their character position. While these functions don't exist natively in PHP's core string API, achieving the same logic is straightforward using built-in array functions or regular expressions. The Java snippet you provided demonstrates a common pattern for parsing delimited messages: extracting content between delimiters based on whether multiple delimiters are present.

To replicate this behavior in PHP, we first need to understand how the logic splits into two distinct cases. If the target string contains only one delimiter, we extract everything after it. If the string contains multiple delimiters, we extract the segment strictly between the first and the last occurrence.

Here is a direct translation of your Java code using PHP's strpos and strrpos functions:

$separator = '-';

// Check if the separator exists in the message
if ($firstIndex = strpos($message, $separator) !== false) {
    // Case 1: Only one delimiter found (or we only care about the first split)
    // In the Java example, this corresponds to indexOf returning a value but lastIndexOf 
    // not being used or returning the same index.
    
    // However, looking closely at the Java logic:
    // If req_type is "RMT", it takes substring(indexOf + 1).
    // Else, it takes substring(indexOf + 1, lastIndexOf).
    
    if ($req_type === 'RMT') {
        $pt_password = substr($message, $firstIndex + 1);
    } else {
        $lastIndex = strrpos($message, $separator);
        
        // Safety check: ensure lastIndexOf is different from firstIndexOf
        // to avoid returning an empty string if they are the same delimiter.
        if ($lastIndex !== false && $lastIndex > $firstIndex) {
            $pt_password = substr($message, $firstIndex + 1, $lastIndex - ($firstIndex + 1));
        } else {
            // Fallback or error handling depending on requirements
            throw new Exception("Invalid delimiter structure found.");
        }
    }
}

The core functions here are strpos (string position) and strrpos (reverse string position). Both return the numeric offset of the first occurrence of the needle, or false if not found. This return type is crucial for PHP developers; unlike Java's indexOf, which often returns -1 for "not found," PHP uses a boolean-like integer comparison against false. Always check explicitly with !== false rather than != false to avoid confusion with the string "0".

When translating the second branch of your code, notice how substr handles the length argument. In Java, the syntax is substring(start, end), where end is exclusive. In PHP, substr(string, length) calculates how many characters to take from the start index. Therefore, calculating the length as $lastIndex - ($firstIndex + 1) ensures we capture exactly what lies between the two dashes without including the final delimiter itself.

A significant trade-off to consider when moving from Java's string methods to PHP is performance on massive datasets. While strpos and strrpos are highly optimized in C, they perform a linear scan of the string. If you are processing millions of messages in real-time, this might become a bottleneck compared to using PCRE (Perl Compatible Regular Expressions) with functions like preg_match. A regex pattern like /-(.*?)-/s could handle the "between first and last" logic in a single pass if your delimiter is complex or if you need case-insensitive matching. However, for simple ASCII delimiters like hyphens, the native array functions are generally faster and more readable due to lower overhead.

If you are building this into a larger application stack using Laravel, consider leveraging helper traits or service classes to encapsulate this parsing logic. While Laravel does not have a native indexOf method on strings, the underlying engine makes these operations extremely efficient. For complex validation requirements surrounding string parsing, packages like illuminate/contracts often provide utility methods that abstract these raw functions into domain-specific behaviors.

Ultimately, while PHP lacks a direct 1:1 mapping to Java's indexOf and lastIndexOf, the combination of strpos, strrpos, and substr offers robust and idiomatic solutions for string manipulation tasks.

Our network