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
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.
#!/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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With