qwertq
asked on
Help with regex
Yea i suck at writing regular expressions. From a string like this:
Foo (Bar)
I need to return Foo and Bar separately. Thanks.
Foo (Bar)
I need to return Foo and Bar separately. Thanks.
/([a-zA-Z]+) \(([a-zA-Z]+)\)/s
ASKER
Thanks for the quick reply. I am having trouble getting it to eval on this string:
Test (Test: Red;Another: + 1.00)
Also, just to check - would it still return $hits[0] if the second part in the () is not there?
Test (Test: Red;Another: + 1.00)
Also, just to check - would it still return $hits[0] if the second part in the () is not there?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Can't you use a * for everything inside the ()?
that would be the dot (.) making the regexp look like this:
'/([a-zA-Z]+) \((.+)\)/s'
however, i'm would not use the dot if there is an other way, because the dot will match some more stuff, e.g. like this
"Foo (Bar) Foo (Bar)"
Now this regexp will find two hits:
1. Foo
2. Bar) Foo (Bar
which is not quite what you might be expecting.
'/([a-zA-Z]+) \((.+)\)/s'
however, i'm would not use the dot if there is an other way, because the dot will match some more stuff, e.g. like this
"Foo (Bar) Foo (Bar)"
Now this regexp will find two hits:
1. Foo
2. Bar) Foo (Bar
which is not quite what you might be expecting.
$matches[2] would be empty if the string did not contain ( ):
Raw Match Pattern:
([^(]+)(?:\(([^)]*)\))?
PHP Code Example:
<?php
$sourcestring="your source string";
preg_match('/([^(]+)(?:\(([^)]*)\))?/',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>
$matches Array:
(
[0] => Test (Test: Red;Another: + 1.00)
[1] => Test
[2] => Test: Red;Another: + 1.00
)