PHP: Best way to extract text within parenthesis?

PHP: Best way to extract text within parenthesis?

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

Stefan Bogdanescu

Founder & Senior Architect

PHP: Best way to extract text within parenthesis?

When parsing strings like "ignore everything except this (text)" to isolate the content inside parentheses, the goal is often to find a balance between raw performance and code clarity. The approach you presented uses strpos, strlen, and substr. While this method involves three function calls, it is actually quite robust for simple cases where the delimiter characters are guaranteed to exist exactly once in the string.

However, relying solely on character position calculations can become brittle if your input data varies. Consider a scenario where the string contains multiple sets of parentheses, such as "Version (1.0) and (2.0)". Your current logic would stop at the first closing parenthesis, returning only (1.0). If you need to handle nested structures or multiple occurrences without defining a specific count, your manual index calculation won't automatically adapt to extract the last match.

The Regex Alternative

In PHP, regular expressions are often dismissed as inefficient due to their overhead. This reputation stems from using complex patterns on massive datasets where every character needs scanning. However, for the specific task of extracting content between delimiters, a well-crafted regex can be both concise and performant.

Using preg_match, you can capture the text directly:

$fullString = "ignore everything except this (text)";
if (preg_match('/\(([^)]+)\)/', $fullString, $matches)) {
    echo $matches[1]; // Outputs: text
}

This pattern \(([^)]+)\) works by looking for an opening parenthesis (, then capturing any characters that are not a closing parenthesis ), and finally expecting a closing parenthesis. The [^)]+ part is crucial; it ensures the match stops at the first encountered closing parenthesis, preventing it from consuming content meant for subsequent groups.

Performance Trade-offs

If raw speed is your primary concern, function call overhead matters less than algorithmic complexity. Your string manipulation method has a time complexity of O(n) because strpos and substr must scan parts of the string. Similarly, preg_match operates in O(n) for this specific pattern because it doesn't need to backtrack if the first parenthesis is found early.

The deciding factor isn't strictly function count but rather what happens with malformed data. Your manual approach will return a result even if the closing parenthesis is missing; it simply calculates the distance from the open bracket to the end of the string. This might be acceptable depending on your error handling strategy, but it risks returning garbage data like "text)" or empty strings if the opening bracket is missing.

Regex offers better semantic safety here. If you anchor your expectation to the pattern structure, a failed match indicates a structural problem in the data immediately. For example, using preg_match_all allows you to extract all instances:

$fullString = "Settings (dev) or Settings (prod)";
if (preg_match_all('/\(([^)]+)\)/', $fullString, $matches)) {
    print_r($matches[1]); 
}
// Output: Array ( [0] => dev [1] => prod )

When to Use Which Method

Your original solution is perfectly fine if you are certain of the string format and only need the first occurrence. It requires no regex engine initialization, which makes it theoretically faster in a tight loop processing millions of identical strings where the pattern never changes. The JIT compiler in modern PHP versions handles simple string functions extremely well.

However, if your application processes diverse user inputs or dynamic logs where the number of parentheses varies, switching to preg_match pays dividends in code maintainability. It abstracts the "find open, find close" logic into a declarative statement that clearly describes intent.

For high-throughput scenarios where performance is critical, benchmarking with your specific dataset is always recommended. But generally, the readability of regex outweighs its slight overhead for this particular extraction task. If you are working within the Laravel ecosystem, tools like Str helper methods often wrap these concepts to provide even cleaner syntax, though understanding the underlying mechanics remains essential for debugging edge cases.

Our network