SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Mar 2005
    Posts
    231
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Splitting numbers from text in string/

    I got a column in my msyql database that didn't import correctly that merged two columns from my csv.

    I want to loop through my records and do something to this field but what I want to know is how to do this with php?

    I assume I'd use the split() function but how do i determine which part is the number?

    the field values are like this 00001ACTUATOR, 00001ADAPTER, etc.

    What I don't know how to do is to determine the number in the beginning of the string from the text?
    How would I go about this?

    Thanks

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    A regular expression makes stuff like this easy
    PHP Code:
    preg_match('#^(\d+)(.+)#s'$text$matches);
    list (
    $leading_digits$the_rest) = $matches
    But, you could have also just used string functions as well. This counts how many leading digits there are in the string, and then uses it to split the string at that position.
    PHP Code:
    $i 0;
    while (isset(
    $text[$i]) && ctype_digit($text[$i])) {
        
    $i++;
    }
    $leading_digits substr($text0$i);
    $the_rest substr($text$i); 

  3. #3
    @php.net Salathe's Avatar
    Join Date
    Dec 2004
    Location
    Edinburgh
    Posts
    1,396
    Mentioned
    54 Post(s)
    Tagged
    0 Thread(s)
    You could also use another string function, sscanf which is used to interpret a string according to a particular format.

    PHP Code:
    $string '00001ACTUATOR';
    list(
    $number$word) = sscanf($string'%05s%s');
    var_dump($number$word); 
    Which will output something like:

    string(5) "00001"
    string(8) "ACTUATOR"


    If you want the $number to be an integer, replace %05s with %05d.
    Salathe
    Software Developer and PHP Manual Author.


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
  •