How to find numbers in a string

Discussion in 'PHP' started by MajHate, May 9, 2009.

  1. #1
    Hello,

    I am trying to find out out many numbers there are in a string. So if I have:

    Jason90

    I would want to get those values 9 and 0 and know that there are two integers.

    Thank You,
    Jason
     
    MajHate, May 9, 2009 IP
  2. Estevan

    Estevan Peon

    Messages:
    120
    Likes Received:
    8
    Best Answers:
    1
    Trophy Points:
    0
    #2
    hello

    here is a lite example
    <?php
    $ms="Site321";
    $string = ereg_replace("[^0-9]", "",$ms);
    echo $string;
    ?>
    PHP:
     
    Estevan, May 9, 2009 IP
  3. GreenWithEnvy

    GreenWithEnvy Active Member

    Messages:
    125
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    53
    #3
    You may be looking for something more like this:
    <?php
    $subject = "GreenWithEnvy15";
    preg_match_all('/[0-9]/', $subject, $matches);
    $count = count($matches[0]);
    echo $count; //echos number of integers in $subject
    ?>
    PHP:
     
    GreenWithEnvy, May 10, 2009 IP
  4. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #4
    echo strlen(preg_replace('#[^\d]+#', '', $string));
    PHP:
     
    joebert, May 11, 2009 IP
  5. somanweb

    somanweb Peon

    Messages:
    21
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Hi,

    if you want get / print the value of numbers , you can use this code in the bottom of the "GreenWithEnvy" code

    for ($i = 0 ; $i < $count ; $i++ )
    {
    echo $matches[0][$i];
    echo '<br/>';

    }

    Soman
     
    somanweb, May 11, 2009 IP
  6. dplover147

    dplover147 Member

    Messages:
    120
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    36
    #6
    I think this line is enough
    preg_replace("/[^0-9]/","",$string);
    PHP:
     
    dplover147, Dec 27, 2011 IP
  7. visualgaurd

    visualgaurd Peon

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    all code is going well and it's true in it's sound. it's good and thanks for the post.
     
    visualgaurd, Dec 27, 2011 IP