[RESOLVED] Retrieving part of a string
Hi,
Basically I want to extract "foo" from the string "(foo)bar", where the only constants are the parentheses.
The method I'm using now:
PHP Code:
$tmp = explode('(', $input);
$tmp2 = explode(')', $tmp[1]);
$output = $tmp2[0];
In my opinion very inefficient, but I can't think of anything else at the moment.
Any hints?
Thanks.
Re: Retrieving part of a string
Welcome to the wonderful world of regular expressions.
Code:
$input="(foo)bar";
preg_match("/[^(]*\(([^)]*)\).*/",$input,$matches);
print_r($matches); //"foo" is in $matches[1]
Regex is a big topic that I'd recommend Googling for an introduction and some examples to learn from. Its purpose is string processing based on flexible patterns.
Re: Retrieving part of a string
try:
PHP Code:
if (preg_match('/^\(([^\)])*\)/', $input, $matches))
$output = $matches[1];
(untested...)
Re: Retrieving part of a string
Re: Retrieving part of a string
Yeah, I figured it would be regex :D
But my knowledge of it is really fragmented, still need to take some time to study that.
If it isn't too much trouble, would you mind explaining the expression?
What I seem to understand so far is that with [^(]* it matches anything that isn't brackets, right?
Thanks anyway :)
Re: Retrieving part of a string
Square brackets make up a character class:
[a] will match one instance of the character 'a'
[ab] will match either 'a' or 'b'
[a]* will match 'a' any number of times, including zero
[ab]* will match '', 'a', 'b', 'ab', 'ba', 'aba', and so on
The ^ symbol is used for negation:
[^a] will match any character except for 'a'
[^a]* will match any string which doesn't contain 'a'.
Re: Retrieving part of a string
yes. the expression ([^)])* basically says to match zero or more characters (*) that are not (^) a closing bracket (")"). the brackets surrounding this expression mean that you want to store whatever is matched there. the end expression, .* says to match any character zero or more times (which would match bar in your example), but does not store it.
oops! I guess penagate got here first ;)
Re: Retrieving part of a string
Re: Retrieving part of a string
I could see you were both on the thread when I was going to reply... Figured I'd just sit back and watch. :]
Re: Retrieving part of a string
I see. And what's the \( and \) for?
Thanks for all the replies
Re: Retrieving part of a string
backslashes in PHP are pretty much always for escaping characters. parenthesis in regular expressions are special characters, just like square brackets, the asterisk, period, and addition signs are. these must be escaped if you want to match for them in a regular expression. you're escaping them in this case because you want to match a string enclosed within them, hence \(([^)])*\).
Re: [RESOLVED] Retrieving part of a string
Thanks, that's clear now :)