split string

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

split string

Post by yaron »

Hello all,

I want to split a string to 3 substrings.
my string format is :

'first part' 'second part' 'third part'

whitespace is deviding each part but the third part conatin whitspaces as well so I can't use explode(' ',$str) becasue it will devide the third part to many subs as well.

and thoughts?
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Is there no way you could add another delimiter? It would be possible to split the string as is (if those single quotes are part of it) but it would be much easier if it were, for example pipe (|) delimited:

Code: Select all

$string = "'first part' | 'second part' | 'third part'";
$parts = explode(' | ', $string);
Mac
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

Post by yaron »

if I knew where to put the delimiter '|' then I wouldn't have any problem.
the string is coming out of a file.
What I need is to explode only the first 2 ones devided by whitespace and the third one is on it's own and can contain whitespaces
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

Post by scorphus »

You could try it:

Code: Select all

<?php
$str = 'part1 part2 part3 that contains white spaces as well';
$parts = explode(' ', $str);
$first = $parts[0];
$secon = $parts[1];
$third = $parts[2];
for ($i = 3; $i < count($parts); $i++)
	$third .= ' ' . $parts[$i];

echo $first, "\n";
echo $secon, "\n";
echo $third, "\n";
?>
output:

Code: Select all

part1
part2
part3 that contains white spaces as well
Regards,
Scorphus.
yaron
Forum Contributor
Posts: 157
Joined: Fri Aug 22, 2003 8:40 am

Post by yaron »

thanks.. i'll do that
Post Reply