note 60032 added to function.split

From: Date: Fri, 23 Dec 2005 13:32:58 +0000
Subject: note 60032 added to function.split
Groups: php.notes 
Request: Send a blank email to php-notes+get-100617@lists.php.net to get a copy of this message
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; } ---- Manual Page -- http://www.php.net/manual/en/function.split.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+60032 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+60032&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+60032&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+60032&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+60032&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+60032&report=yes&reason=non-english Delete: already in docs -- http://master.php.net/manage/user-notes.php?action=delete+60032&report=yes&reason=already+in+docs Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+60032&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+60032&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#100617) next »