note 60032 deleted from function.split by nlopess

From: Date: Fri, 23 Dec 2005 18:54:03 +0000
Subject: note 60032 deleted from function.split by nlopess
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-100630@lists.php.net to get a copy of this message
Note Submitter: http://www.skobba.com Reason: useless ---- I needed an function which splitted an string on regular expression (preg_split) BUT also left everything within "" intact, and it should be used on strings not neccesarily consistent (i.e. correct number of "). Example $str=' " tore er " kul " tore " er kul,"frue,tore", nice'; Should be in an array: [0] => frue,tore [1] => tore [2] => tore er [3] => kul [4] => er [5] => kul [6] => nice This was my solution, note it returns false if the numbers of " are not even. This can easily be changed by adjusting the code at the bottom. This is my first contribution to the PHP manuall (I usally do Java). Any feedback is wanted. /* First it parses out all strings which are between "", then it uses the reg_ex to split the rest @str The string to split @reg_ex The regular expression to split everything not within ". @return An array of strings of split ok, returns false if there are not even " in the @str */ function splitter($str,$reg_ex) { $strleft=$str; $formerpos=-1; $i=0; $keywords=array(); $numkeywords=0; while ($pos=strripos($strleft,'"')) { $i=$i+1; if($pos>0 && $formerpos==-1) $formerpos=$pos; else if ($pos>0 && $formerpos>-1) { $keywords[$numkeywords]=substr($strleft,$pos+1,$formerpos-$pos-1); $keywords[$numkeywords]=trim($keywords[$numkeywords]); $strleft=substr($strleft,0,$pos).substr($strleft,$formerpos); $formerpos=-1; $numkeywords=$numkeywords+1; } $strleft=substr($strleft,0,$pos).substr($strleft,$pos+1); // echo 'String left is: '.$strleft; } if (($i - (2*floor($i/2)))==0) { // Now spilt the rest of the keywords return array_merge($keywords,preg_split($reg_ex, trim($strleft))); } else return false; }

« previous php.notes (#100630) next »