I'm trying to devise a regexp that extracts:
aa
bb
cc
from the subject:
aa,bb,cc
I'm using the following regexp:
|(.+?),*|
but the result is
a
a
b
b
c
c
Please help,
Thanks.
I'm trying to devise a regexp that extracts:
aa
bb
cc
from the subject:
aa,bb,cc
I'm using the following regexp:
|(.+?),*|
but the result is
a
a
b
b
c
c
Please help,
Thanks.
Get the matched group from index 1.
(\w+),?
Sample code:
$re = "/(\\w+),?/m";
$str = "aa,bb,cc";
preg_match_all($re, $str, $matches);
You can use PHP: Split string as well using explode:
$myArray = explode(',', $myString);
Read more How can I split a comma delimited string into an array in PHP?
The ?
makes your match 'non-greedy', that means it will match the shortest possible string that satisfies the regular expression. Also, ,*
means 0 or more commas
.
What you're looking for is:
|[^,]+|
For example:
<?php
$foo = "aa,bb,cc";
preg_match_all("/[^,]+/",$foo,$matches);
for($j=0;$j<count($matches[0]); $j++){
print $matches[0][$j] . "\n";
}
?>
Without any groups,
(?<=^|,)\w+
OR
\w+(?=,|$)
PHP code would be,
<?php
$data = "aa,bb,cc";
$regex = '~(?<=^|,)\w+~';
preg_match_all($regex, $data, $matches);
var_dump($matches);
?>
Output:
array(1) {
[0]=>
array(3) {
[0]=>
string(2) "aa"
[1]=>
string(2) "bb"
[2]=>
string(2) "cc"
}
}