Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Aug 2007
    Posts
    58
    Thanks
    2
    Thanked 6 Times in 6 Posts

    Splitting a string

    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.
    Last edited by Blue_Jeans; 11-18-2007 at 01:32 AM.

  • #2
    New Coder
    Join Date
    Nov 2007
    Posts
    12
    Thanks
    0
    Thanked 1 Time in 1 Post
    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 Code:
    <?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>';

    ?>
    Last edited by phpBuddy; 11-18-2007 at 08:37 AM.
    echo "PHP 5.2.5";
    exit ( "Script End" );


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •