Although you might not store data in text files in comma delimited format you may well have to import some data from files like that.  You are presented with a long string of data with the different parts separated in some way.  Create a new page called stringsplit.php and add this under the h1:

$inventory="item01:cutlass, item02:dagger, item03:wooden, item04:shield, item05:water";
$items=explode(",", $inventory);

The idea is that for some reason when playing a game the things the gamer owns are listed in a text file (unlikely as they would be in a database).

The explode function looks for commas and splits the string where it sees one.  You now have an array of individual items which you could loop through and do things with.  Add this:

echo "<p>Your inventory items are:</p>";
echo "<ul>";
foreach($items as $item){
    echo "<li>$item</li>";
echo "</ul>";

Trim again

If you look carefully at the items displayed in the list there is a space at the end of most of them (view page source to see them).  To get rid of the spaces just add this as the new first line inside the foreach:


Before you echo each item you are now removing the extra space character.


You can also just split a string based on a position.  In the current list assume that we do not want to show the item number.  Add this under the trim line:

$item=substr($item, 7);

Try it.  The substr() function takes the string and grabs just the bit starting at the numbered character (7).

Substring length

If you only wanted a set number of characters you can add a third parameter/argument to the function call.  For example (don't do this):

  $item=substr($item, 7, 1);

That would get just the first letter of each item.  The second number is the length of string you want from the start position which is the first number.