note 112400 added to function.preg-replace

From: Date: Wed, 12 Jun 2013 08:02:22 +0000
Subject: note 112400 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-195136@lists.php.net to get a copy of this message
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 ---- Server IP: 69.147.83.199 Probable Submitter: 79.116.216.149 ---- Manual Page -- http://php.net/manual/en/function.preg-replace.php Edit -- https://master.php.net/note/edit/112400 Del: integrated -- https://master.php.net/note/delete/112400/integrated Del: useless -- https://master.php.net/note/delete/112400/useless Del: bad code -- https://master.php.net/note/delete/112400/bad+code Del: spam -- https://master.php.net/note/delete/112400/spam Del: non-english -- https://master.php.net/note/delete/112400/non-english Del: in docs -- https://master.php.net/note/delete/112400/in+docs Del: other reasons-- https://master.php.net/note/delete/112400 Reject -- https://master.php.net/note/reject/112400 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#195136) next »