Results 1 to 2 of 2

Thread: question about preg_match

  1. #1
    Join Date
    Jan 2010
    Posts
    13
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default question about preg_match

    hi

    i was told that preg_match can be used to split strings and store them in arrays
    how does preg_match actually works?

    for example i would like to store this string in an array
    $text = '720101-11-5903 (A2037135)';

    i want it to be like this

    $arr[0] = 720101-11-5903
    $arr[1] = A2037135

    thanks. help would be much appreciated

  2. #2
    Join Date
    Jan 2007
    Location
    Davenport, Iowa
    Posts
    2,385
    Thanks
    100
    Thanked 113 Times in 111 Posts

    Default

    Hi,

    I am sure there is a better way to do this, but try this:
    PHP Code:
    <?php
    $text 
    '720101-11-5903 (A2037135)';
    $text=preg_split('/[^a-zA-Z0-9\-]/',$text);
    foreach(
    $text as $key => $value) { 
      if(
    $value == "") { 
        unset(
    $text[$key]); 
      } 
    }
    print_r($text);
    ?>
    preg_match will match what you are looking for and put it into an array. Preg_match is a good way to look for a needle in a haystack of code or text. It is handy in the sense that it will not do anything to the string like preg_split or preg_replace or whatever, but the problem is that if you want to match more than the first match in your string/variable then you will need to use preg_match_all, which will store all of your matches into a multidimensional array, which can get a bit more complicated.

    In your post you said that you wanted to split the string, so I used preg_split.

    If it were me I would not use a regular expression at all and would do something like:
    PHP Code:
    <?php
    $text 
    '720101-11-5903 (A2037135)';
    $text=str_replace(array('(',')'),'',$text);
    $text=explode(' ',$text);
    print_r($text);
    ?>
    The reason being that str_replace is simpler and requires a lot less processor power. It is more efficient and much more efficient.
    Last edited by james438; 02-26-2010 at 07:31 AM. Reason: grammar
    To choose the lesser of two evils is still to choose evil. My personal site

  3. The Following User Says Thank You to james438 For This Useful Post:

    awakener1986 (03-02-2010)

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
  •