PHP: Best way to extract text within parenthesis? PHP: Best way to extract text within parenthesis? php php

PHP: Best way to extract text within parenthesis?


i'd just do a regex and get it over with. unless you are doing enough iterations that it becomes a huge performance issue, it's just easier to code (and understand when you look back on it)

$text = 'ignore everything except this (text)';preg_match('#\((.*?)\)#', $text, $match);print $match[1];


So, actually, the code you posted doesn't work: substr()'s parameters are $string, $start and $length, and strpos()'s parameters are $haystack, $needle. Slightly modified:

$str = "ignore everything except this (text)";$start  = strpos($str, '(');$end    = strpos($str, ')', $start + 1);$length = $end - $start;$result = substr($str, $start + 1, $length - 1);

Some subtleties: I used $start + 1 in the offset parameter in order to help PHP out while doing the strpos() search on the second parenthesis; we increment $start one and reduce $length to exclude the parentheses from the match.

Also, there's no error checking in this code: you'll want to make sure $start and $end do not === false before performing the substr.

As for using strpos/substr versus regex; performance-wise, this code will beat a regular expression hands down. It's a little wordier though. I eat and breathe strpos/substr, so I don't mind this too much, but someone else may prefer the compactness of a regex.


Use a regular expression:

if( preg_match( '!\(([^\)]+)\)!', $text, $match ) )    $text = $match[1];