Reputation: 279
here is a long string like"abc,adbc,abcf,abc,adbc,abcf"
I want to use regex to remove the duplicate strings which are seperated by comma
the following is my codes, but the result is not what I expect.
$a='abc,adbc,abcf,abc,adbc,abcf';
$b=preg_replace('/(,[^,]+,)(?=.*?\1)/',',',','.$a.',');
echo $b;
output:,adbc,abc,adbc,abcf,
It should be : ,abc,adbc,abcf,
please point my problem. thanks.
Upvotes: 2
Views: 1552
Reputation: 16086
Here I am sharing simple php logic instead regex
$a='abc,adbc,abcf,abc,adbc,abcf';
$pieces = explode(",", $a);
$unique_values = array_unique($pieces);
$string = implode(",", $unique_values);
Upvotes: 3
Reputation: 7207
Try this....
$string='abc,adbc,abcf,abc,adbc,abcf';
$exp = explode(",", $string);
$arr = array_unique($exp);
$output=implode(',', $arr);
Upvotes: 0
Reputation: 3534
You can also try
echo implode(",", array_unique(preg_split(",", $yourLongString)));
Upvotes: 0
Reputation: 3878
Here is positive lookahead base attempt on regex based solution to OP's problem.
$arr = array('ball ball code', 'abcabc bde bde', 'awycodeawy');
foreach($arr as $str)
echo "'$str' => '" . preg_replace('/(\w{2,})(?=.*?\\1)\W*/', '', $str) ."'\n";
OUTPUT
'ball ball code' => 'ball code'
'abcabc bde bde' => 'abc bde'
'awycodeawy' => 'codeawy'
As you can for the input 'awycodeawy' it makes it to 'codeawy' instead of 'awycode'. The reason is that it is possible to find a variable length lookahead something which is not possible for lookbehind.
Upvotes: 0