Reputation: 7599
I have some text like:
name: [my_name]
email: [my_email]
I'd like to grab the fields in square brackets with regex—how would I do that?
I've tried using this pattern: [*.?]
Unfortunately it doesn't work. PHP gives this error:
compilation failed: nothing to repeat at offset 0
What's wrong? Is the pattern correct?
Upvotes: 1
Views: 325
Reputation: 9168
[
and ]
special characters, so you need to escape them:
\[*.?\]
Upvotes: 0
Reputation: 4105
<?php
$text =
"name: [my_name]
email: [my_email]";
$pattern = '/\[(.*)\]/';
$matches = array();
preg_match_all($pattern, $text, $matches);
$name = $matches[1][0];
$email = $matches[1][1];
print "$name<br />";
print "$email";
?>
will output
my_name
my_email
/
is the delimiter (not part of the actual pattern per se). The \
is for escaping the [
and ]
brackets, as they define character class definitions in patterns when not escaped. (
and )
define subpatterns, which means that text captured by a subpattern will be put into the array referenced by the third parameter of preg_match_all
(in this case $matches
).
Upvotes: 1
Reputation: 25791
No, you got the order wrong. It should be something like
\[(.*)\]
.* = Something repeated as many times as possible.
The compilation error you get is because the compiler does not now what to repeat, as [ is a special character in regular expressions. The ?
you added would also allow nothing within the brackets, which I figured you don't want, so I removed it. The question mark makes the foregoing statement optional. The parentheses aroudn the .*
are used to capture the result. If you don't add those, the regex will match, but you won't get whats inside the brackets as result.
Upvotes: 1
Reputation: 32596
The brackets are special characters in regex. To match them you'll have to escape them with a back-slash. Something like \[(.*?)\]
. Adding the parens ()
captures whatever is matched inside it so you you can use it later. Otherwise you're just matching on the whole pattern and you'd have to manually strip the brackets.
Upvotes: 3
Reputation: 4064
You should move the * and escape the [ and ]. So make it \[.*\]
Since . matches any character already and * says: 0 or more of that char. So .* is 0 or more of any char
Upvotes: 1