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('/^(\开发者_如何学Pythonw+)-(?=\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.
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
精彩评论