Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Splitting a string in PHP

  • 15-11-2007 05:57PM
    #1
    Registered Users, Registered Users 2 Posts: 35,522 ✭✭✭✭


    I am slowly (very slowly..) learning PHP and there is something I'd like to be able to do which involves splitting a string of numbers.

    I have an outputted number eg: 146
    I would like to turn this into: <img src="1.jpg" /><img src="4.jpg" /><img src="6.jpg" />

    I've looked into explode and split functions but all of them seem to need a delimiter in the string.

    Anybody any ideas as to what php function I need to Google?


Comments

  • Registered Users, Registered Users 2 Posts: 68,173 ✭✭✭✭seamus


    split() should still work without a delimter. OK, well not without one, but with an empty string, i.e.

    split("", myString);

    You should also be able to iterate through the string and get each character in turn;
    for($i = 0; $i < strlen(myString); $i++) {
    $char = substr(myString, $i, 1);
    echo '<img src="$char.jpg" />';
    }
    


  • Registered Users, Registered Users 2 Posts: 2,934 ✭✭✭egan007


    <?php


    $string = "12345";

    $chars = preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY);

    foreach($chars as $image){
    $list .= "<img src=\"./$image.jpg\">";
    }
    echo $list;

    ?>


  • Registered Users, Registered Users 2 Posts: 35,522 ✭✭✭✭Gordon


    You guys rock, thank you so much :)

    Now I'm going to have to dissect both of your codes and try to understand why they both work and how they both work!

    Cheers.


Advertisement