Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consolidating duplicates with preg_replace, take into consideration dash

I have a preg_replace that finds duplicate entries and consolidates. I need to take into consideration the dash as well, but currently it does not.

$id = KRS-KRS-123
preg_replace('/^(\w+)-(?=\1)/', '', $id);
// returns KRS-123

$id = KRS-KRS123
preg_replace('/^(\w+)-(?=\1)/', '', $id)
// returns KRS123
// I need this one to return KRS-KRS123
like image 304
kylex Avatar asked Jan 22 '26 09:01

kylex


1 Answers

Add a word boundary, \b, after the \1 inside the look ahead (?=\1\b):

preg_replace('/^(\w+)-(?=\1\b)/', '', $id);

That way, the lookahead will only evaluate to true if \1 is followed by a \W (a [^\w]) or the end-of-string.

Demo

#!/usr/bin/env php
<?php
$s = 'KRS-KRS-123
KRS-KRS123';
echo preg_replace('/^(\w+)-(?=\1\b)/m', '', $s);
?>

will produce:

KRS-123
KRS-KRS123
like image 199
Bart Kiers Avatar answered Jan 24 '26 22:01

Bart Kiers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!