note 108122 added to function.str-replace

From: Date: Fri, 30 Mar 2012 10:34:18 +0000
Subject: note 108122 added to function.str-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-186913@lists.php.net to get a copy of this message
If you want to replace only a specific occurance of a needle, you can use this handy function: <?php function str_replace_occurance($search, $replace, $subject, $occurance) { $pos = 0; for ($i = 0; $i <= $occurance; $i++) { $pos = strpos($subject, $search, $pos); } return substr_replace($subject, $replace, $pos, strlen($search)); } $str = "hello world! hello again! say hello!"; $str = str_replace_occurance('hello', 'hi', $str, 1); $str = str_replace_occurance('hello', 'lets do this', $str, 2); echo $str, PHP_EOL; ?> Example output: "hi world! lets do this again! say hello!" ---- Server IP: 87.106.1.137 Probable Submitter: 87.193.161.154 ---- Manual Page -- http://www.php.net/manual/en/function.str-replace.php Edit -- https://master.php.net/note/edit/108122 Del: integrated -- https://master.php.net/note/delete/108122/integrated Del: useless -- https://master.php.net/note/delete/108122/useless Del: bad code -- https://master.php.net/note/delete/108122/bad+code Del: spam -- https://master.php.net/note/delete/108122/spam Del: non-english -- https://master.php.net/note/delete/108122/non-english Del: in docs -- https://master.php.net/note/delete/108122/in+docs Del: other reasons-- https://master.php.net/note/delete/108122 Reject -- https://master.php.net/note/reject/108122 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186913) next »