SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru
    Join Date
    Oct 2004
    Location
    uk
    Posts
    853
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Get string in between certain characters

    Hi guys

    I need to get the number after each v and echo it out


    PHP Code:
    $var="v9v10v11v12"
    What would be the best way to do this?

  2. #2
    SitePoint Mentor bronze trophy
    John_Betong's Avatar
    Join Date
    Aug 2005
    Location
    City of Angels
    Posts
    1,819
    Mentioned
    73 Post(s)
    Tagged
    6 Thread(s)
    Quote Originally Posted by wazo View Post
    Hi guys

    I need to get the number after each v and echo it out


    PHP Code:
    $var="v9v10v11v12"
    What would be the best way to do this?
    Try str_replace(...) or implode(...) and explode(...) to get individual numbers into an array().
    Last edited by John_Betong; Mar 24, 2013 at 14:38. Reason: formatting

  3. #3
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,629
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Example of explode ...

    PHP Code:
    <?php
    $str
    ="v9v10v11v12";
    $arr=explode("v",$str);
    foreach (
    $arr as $key=>$val) {
        echo 
    $key ." is "$val ."<br>";
    }
    ?>
    or

    PHP Code:
    <?php
    $str
    ="v9v10v11v12";
    $arr=explode("v",$str);
    var_dump($arr);
    ?>
    Ian Anderson
    www.siteguru.co.uk

  4. #4
    Keeper of the SFL StarLion's Avatar
    Join Date
    Feb 2006
    Location
    Atlanta, GA, USA
    Posts
    3,748
    Mentioned
    71 Post(s)
    Tagged
    0 Thread(s)
    Just beware that the first element of your array will be empty if you use explode on a string that begins with v.
    You can handle this by ignoring the first element, array_shift'ing it off the front of the array, or by using preg_split with the appropriate flag instead;
    PHP Code:
    foreach ($arr as $key=>$val) {
        if(
    $key != 0) { echo $key ." is "$val ."<br>"; }

    PHP Code:
    array_shift($arr); 

    PHP Code:
    $arr preg_split("~v~",$str,-1,PREG_SPLIT_NO_EMPTY); 
    Never grow up. The instant you do, you lose all ability to imagine great things, for fear of reality crashing in.


Bookmarks

Posting Permissions

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