How do you split a string using split()?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View
I have this PHP statement which works fine and breaks down a string of
lines delimited with a \r into an array.

$arrList=split("\r", $strList);

But what I really want is to be able to tell it to split out only the
strings that start with the letter "b".

E.g. I thought this would work "b\W\r"

I tried every regular expression but cant figure it out. I could use
some other function combinations to achive this but I though if there
is a way to do it with just spli()

Any ideas?

Re: How do you split a string using split()?

Your regular expression would probably look something like this:


For a line that begins with the letter 'b' is followed by one or more
'anything', ending with '\r'.

You would split the file into multiple lines with split(), then pass
each line to preg_match as $inputLine.

So you could use:

$numParts = preg_match($expression,$inputLine,$arrMatches);

Maybe theres a simpler way, I'm tired |-)

Re: How do you split a string using split()?

Carved in mystic runes upon the very living rock, the last words of ImOk  
of comp.lang.php make plain:

Quoted text here. Click to load it

Since split() deletes the delimiter string that it's splitting on, I  
don't think that function is going to give you what you want, regardless  
of regex.

Try the preg_match_all() function.

An alternative would be to convert the appropriate \r characters to  
something else unlikely to be in the string (such as a , for example),  
and split on that:

$strList = preg_replace("/(b.+)\r/U", "", $strList);
$arrList = explode("", $strList);

Alan Little
Phorm PHP Form Processor

Re: How do you split a string using split()?

Based on your suggestions, I finally figured out a solution.

$arrList=split("\r", $strList);

Split string into the array components and using preg_grep filter only
the elements that start with 'b'


Site Timeline