Duplicate Consolidation

I am working on a script that develops specific strings of alphanumeric characters, separated by dashes. I need to check the string to see if there are any character sets (characters that are between the dashes) that are the same. If they are, I need to consolidate them. Duplicate characters will always occur in front in my case.

 Examples: KRS-KRS-454-L would become: KRS-454-L DERP-DERP-545-P would become: DERP-545-P 
+8
php regex
source share
4 answers
 <?php $s = 'KRS-KRS-454-L'; echo preg_replace('/^(\w+)-(?=\1)/', '', $s); ?> // KRS-454-L 

A positive result is used to check duplicate lines (?=...) .

Note that \w also contains an underscore. If you want to limit only to alphanumeric characters, use [a-zA-Z0-9] .

In addition, I got attached to ^ , as you already mentioned: "Duplicate characters will always occur in front [...]"

+10
source share

Try the template:

 /([az]+)(?:-\1)*(.*)/i 

and replace it with:

 $1$2 

Demonstration:

 $tests = array( 'KRS-KRS-454-L', 'DERP-DERP-DERP-545-P', 'OKAY-666-A' ); foreach ($tests as $t) { echo preg_replace('/([az]+)(?:-\1)*(.*)/i', '$1$2', $t) . "\n"; } 

gives:

 KRS-454-L DERP-545-P OKAY-666-A 

Brief explanation:

 ([az]+) # group the first "word" in match group 1 (?:-\1)* # match a hyphen followed by what was matched in # group 1, and repeat it zero or more times (.*) # match the rest of the input and store it in group 2 

the replacement string $1$2 is replaced with what corresponded to group 1 and group 2 in the above template.

+3
source share

Use this regular expression ((?:[AZ-])+)\1{1} and replace the matching string with $ 1.

\1 used in connection with {1} in the above regular expression. He will look for a duplicate instance of the characters.

0
source share

You need backlinks . Using perl syntax, this will work for you:

 $line =~ s/([A-Za-z0-9]+-)\1+/\1/gi; 
0
source share

All Articles