I have a string of numbers surrounded by parenthesis:
(2)(56)(9)(12)(2)
I was given the following regex by someone to split the numbers out of their parentheses:
<?php
$string = '(2)(56)(9)(12)(2)';
$pattern = "/\\)\\(|\\(|\\)?/";
$numbers = preg_split($pattern, $string);
foreach ($numbers as $number) {
echo $number.'<br />';
}
?>
This outputs:
<br />
<br />
2<br />
<br />
5<br />
6<br />
<br />
9<br />
<br />
1<br />
2<br />
<br />
2<br />
<br />
<br />
When I really need it to output:
2<br />
56<br />
9<br />
12<br />
2<br />
How can the regex be altered to make it work?
ps each number in between the parenthesis can be of an unlimited length.
I would not use preg_split in the first place. If that's really your source string, then look just for numbers:
preg_match_all("/\d+/", $string, $numbers);
print_r($numbers[0]);
First, there's an error in the regex. It should be:
$pattern = "/\\)\\(|\\(|\\)/";
Note the last ?
is removed.
The easy answer is to just check for empty numbers:
foreach ($numbers as $number) {
if ($number !== '') {
echo $number.'<br />';
}
}
Note the strict !==
test since 0
may be a valid number...
Or, add the PREG_SPLIT_NO_EMPTY
option to the preg_split
call:
$numbers = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY);
Another option is to use preg_match_all
with the simple regex: /\\d+/
:
$matches = array();
preg_match_all('/\d+/', $string, $matches);
$numbers = $matches[0];
Use preg_match
instead of split and use /\\\\d+/
as your expression
Try
$string = '(2)(56)(9)(12)(2)';
$pattern = "/\d+/";
preg_match_all($pattern, $string, $numbers);
foreach ($numbers as $number) {
echo $number.'<br />';
}
I'm not sure on PHP regex syntax either \\\\d
or \\d
You just need the PREG_SPLIT_NO_EMPTY option of preg_split, and a small change in the pattern:
$pattern = "/\\)\\(|\\(|\\)/"; // removed the "?"
$numbers = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY); // added PREG_SPLIT_NO_EMPTY
Or use preg_match:
$string = '(2)(56)(9)(12)(2)';
preg_match_all('#\d+#', $string, $matches);
foreach ($matches[0] as $number) {
echo "$number<br />\n";
}
Output:
2<br />
56<br />
9<br />
12<br />
2<br />
Pass the flag PREG_SPLIT_NO_EMPTY
to not return empty tokens and remove the ?
which allows for an empty separator. You also don't need to double-escape the ()
's in PHP. Using preg_match
on (\\d+)
looks like it would be a simpler solution to your problem though.
$string = '(2)(56)(9)(12)(2)';
$pattern = "/\)\(|\(|\)/";
$numbers = preg_split($pattern, $string, -1, PREG_SPLIT_NO_EMPTY);
foreach ($numbers as $number) {
echo "$number<br />\n";
}
Output:
2<br />
56<br />
9<br />
12<br />
2<br />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.