...

View Full Version : Splitting a string



Blue_Jeans
11-18-2007, 01: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.

phpBuddy
11-18-2007, 08:31 AM
Hi
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:
fo.oo-bar.php
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 )
aaa-bbbbbb.txt
then both ways will work

Here are my two suggestions:
<?php

// 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>';

?>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum