View Full Version : Splitting a string

11-18-2007, 02:26 AM
Let's say I have a file name such as foo-bar.ext and I need to parse it into foo and bar and ext. I've done this before, and I cannot remember how I did it. It's a simple little thing, and yet it evades me.

Edit: Naturally, I find the answer after I break down and post a question, lol.

11-18-2007, 09:31 AM
There are a number of ways to do this.
What method you use, depends on what possible character's patterns your string will have.

For example, if your string happens to be:
then the split() below will not give expected result.
But if your string always have the form ( one '-' first and one '.' in the rest of string )
then both ways will work

Here are my two suggestions:

// using strtok()
$string = 'foo-bar.ext';
$a = strtok( $string, '-' );
$b = strtok( '.' );
$c = strtok( '' );

echo $a.'<br>'; echo $b.'<br>'; echo $c.'<br>';
echo '<hr>';

// using split()
$string = 'foo-bar.ext';
list($a, $b, $c) = split( '[-.]', $string );

echo $a.'<br>'; echo $b.'<br>'; echo $c.'<br>';