note 70833 added to function.preg-replace

From: Date: Mon, 30 Oct 2006 23:46:44 +0000
Subject: note 70833 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-119258@lists.php.net to get a copy of this message
Tripped over a subtle issue in preg_replace! Eventually got the right answers from the readers at alt.comp.lang.php! preg_replace assumes a /g - replace all occurences. So, when you need a replacement to force a single / character at end of string, i.e, replace 0 or more / characters with single /, here's what you need: $t = preg_replace('!/*$!', '/', $s, 1); Note the all important 1 (limit) at the end. Default is -1, and it seems to force a non-greedy match for /*$ , so if $s == aa//, the output is still a// with limit -1. But with 1 as the limit, all values of $s such as aa or aa/ or aa// or aa//// all end up like aa/, just as needed. [Not sure why a//// ends up as a// with limit -1...] So, final story, to make *$ be greedy, use the limit of 1. ---- Server IP: 216.194.113.175 Probable Submitter: 216.15.114.45 ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace.php Edit -- https://master.php.net/note/edit/70833 Del: integrated -- https://master.php.net/note/delete/70833/integrated Del: useless -- https://master.php.net/note/delete/70833/useless Del: bad code -- https://master.php.net/note/delete/70833/bad+code Del: spam -- https://master.php.net/note/delete/70833/spam Del: non-english -- https://master.php.net/note/delete/70833/non-english Del: in docs -- https://master.php.net/note/delete/70833/in+docs Del: other reasons-- https://master.php.net/note/delete/70833 Reject -- https://master.php.net/note/reject/70833 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#119258) next »