note 87982 added to function.preg-replace

From: Date: Sun, 04 Jan 2009 20:08:22 +0000
Subject: note 87982 added to function.preg-replace
Groups: php.notes 
Request: Send a blank email to php-notes+get-148828@lists.php.net to get a copy of this message
I was needing regular expression with brace matching, but i was not able to find anything for this problem. So, if i had : \bold{something \underline{another thing} and another bold thing} My regexp would stop at the first closing brace, and it seemed to be a common problem with regular expression, often discussed on forums. So here is the snippet i used, perhaps it'll be useful : <?php function preg_replace_with_braces($Regexp,$Remplacement,$Texte) { preg_match_all($Regexp,$Texte,$Resultats,PREG_SET_ORDER); $SVGRemplacement=$Remplacement; foreach($Resultats as $Resultat) {//For each result $Remplacement=$SVGRemplacement; foreach($Resultat as $n=>$Match) {//For each set of capturing parenthesis if($n>0 && strpos($Match,'{')!==false) {//We find a open brace in our regexp : we'll need to find the closing one ! $InitialMatch=$Match; $Offset=strpos($Texte,$Resultat[0]); $Offset=strpos($Texte,$Match,$Offset);//We move the caret to the good place : let's start ! $Depart=$Offset; $Taille=strlen($Texte); $NestingLevel=0; while($NestingLevel>=0 && $Offset<$Taille) {//Browse the string, searching for braces. Perhaps the most important place ! $Offset++; if($Texte[$Offset]=='{') $NestingLevel++; elseif($Texte[$Offset]=='}') $NestingLevel--; } $Match=substr($Texte,$Depart,$Offset-$Depart); $Resultat[0]=str_replace($InitialMatch,$Match,$Resultat[0]); } $Remplacement=str_replace('$' . $n,$Match,$Remplacement); } $Texte=str_replace($Resultat[0],$Remplacement,$Texte); } return $Texte; } ?> Hope it'll be useful ! I know it's pretty odd and unclean, but that was a quick workaround i had. ---- Server IP: 89.31.146.176 Probable Submitter: 86.67.47.39 ---- Manual Page -- http://www.php.net/manual/en/function.preg-replace.php Edit -- https://master.php.net/note/edit/87982 Del: integrated -- https://master.php.net/note/delete/87982/integrated Del: useless -- https://master.php.net/note/delete/87982/useless Del: bad code -- https://master.php.net/note/delete/87982/bad+code Del: spam -- https://master.php.net/note/delete/87982/spam Del: non-english -- https://master.php.net/note/delete/87982/non-english Del: in docs -- https://master.php.net/note/delete/87982/in+docs Del: other reasons-- https://master.php.net/note/delete/87982 Reject -- https://master.php.net/note/reject/87982 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#148828) next »