如何使用正则表达式替换 PHP 中的重复标点符号?
How to replace repetitive punctuation in PHP using regex?
比方说,我有这个
Hello ??? WHERE ARE YOU!!!! Comon ?!?!?!
desired outout
Hello ? WHERE ARE YOU!!!! Comon ?!
我怎样才能做到这一点?我试过 preg_replace_callback
但没有成功。我用了 as an starting point but it works on complete sentence, I need it to work on word by word + I need to remove duplicate computations only (patterns)? Live Code
将\?+
替换为?
,将!+
替换为!
,将(\?!)+
替换为?!
,依此类推。
function dedup_punctuation($str) {
$targets = array('/\?+/', '/!+/', '/(\?!)+/');
$replacements = array('?' , '!' , '?!' );
return preg_replace($targets, $replacements, $str);
}
使用以下代码:
$str = "Hello ??? WHERE ARE YOU!!!! Comon ?!?!?! ...";
$replacement = [
'?',
'?!',
'.',
];
foreach( $replacement as $key => $value ){
$pattern[$key] = sprintf("/(\%s)+/", $value);
}
echo $outout = preg_replace($pattern, $replacement, $str);
将任何标点符号插入替换数组以删除重复的标点符号。
比方说,我有这个
Hello ??? WHERE ARE YOU!!!! Comon ?!?!?!
desired outout
Hello ? WHERE ARE YOU!!!! Comon ?!
我怎样才能做到这一点?我试过 preg_replace_callback
但没有成功。我用了
将\?+
替换为?
,将!+
替换为!
,将(\?!)+
替换为?!
,依此类推。
function dedup_punctuation($str) {
$targets = array('/\?+/', '/!+/', '/(\?!)+/');
$replacements = array('?' , '!' , '?!' );
return preg_replace($targets, $replacements, $str);
}
使用以下代码:
$str = "Hello ??? WHERE ARE YOU!!!! Comon ?!?!?! ...";
$replacement = [
'?',
'?!',
'.',
];
foreach( $replacement as $key => $value ){
$pattern[$key] = sprintf("/(\%s)+/", $value);
}
echo $outout = preg_replace($pattern, $replacement, $str);
将任何标点符号插入替换数组以删除重复的标点符号。