note 112400 deleted from function.preg-replace by crell
| From: | crell@php.net | Date: | Fri, 01 Jul 2022 19:55:39 +0000 |
| Subject: | note 112400 deleted from function.preg-replace by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218873@lists.php.net to get a copy of this message | ||
Note Submitter: spamthishard at wtriple dot com
----
If you want to replace only the n-th occurrence of $pattern, you can use this function:
<?php
function preg_replace_nth($pattern, $replacement, $subject, $nth=1) {
return preg_replace_callback($pattern,
function($found) use (&$pattern, &$replacement, &$nth) {
$nth--;
if ($nth==0) return preg_replace($pattern, $replacement, reset($found) );
return reset($found);
}, $subject,$nth );
}
echo preg_replace_nth("/(\w+)\|/", '${1} is the 4th|',
"|aa|b|cc|dd|e|ff|gg|kkk|", 4);
?>
this outputs |aa|b|cc|dd is the 4th|e|ff|gg|kkk|
backreferences are accepted in $replacement