2

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.

1
  • maybe you can convert the $a into an array then compare the array to remove duplicate strings Commented Mar 13, 2013 at 6:19

4 Answers 4

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks @SureshKamrushi, can we use a simple regex to solve it?
0

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.

1 Comment

thanks@rajinevitable . if $str='abc adbc abcf abc adbc abcf', it will output "adabcf", supposing a more complicated string, including number or special charactors. like '123abc-90'. what can we do.
0

You can also try

echo implode(",", array_unique(preg_split(",", $yourLongString)));

Comments

0

Try this....

$string='abc,adbc,abcf,abc,adbc,abcf';
$exp = explode(",", $string);
$arr = array_unique($exp);
$output=implode(',', $arr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.