Search code examples
phppreg-matchpreg-match-allpreg-split

Preg split or preg match to extract from string with known and constant pattern


I have a database filled with product names, all of wich follow a strict and identical naming pattern like this European 222/555/111 obtained I want to run a 'for each row in table' little php script and extract the 3 substrings in part 222/555/111 and add the three in separate columns but I'm failing to do the extraction.Should I use preg_split or preg_match? My strings all start with the word 'European' then a space and after that the three options I need separated with /, these could also be only 2 characters like European 96/43/55c strings strings

Should have $option1 = 222 $option2 = 555 $option3 = 111


Solution

  • I'd use preg_match:

    $string = 'European 222/555/111 obtained';
    
    if (preg_match('~European ([^/]+)/([^/]+)/([^/\s]+)~', $string, $matches)) {
        print_r($matches);
    }
    

    Output:

    Array
    (
        [0] => European 222/555/111
        [1] => 222
        [2] => 555
        [3] => 111
    )
    

    Explanation:

    ~               : regex delimiter
      European\s+   : literally "European" followed by one or more space
      ([^/]+)       : match everything that is not a slash and store in group 1
      /             : a slash
      ([^/]+)       : match everything that is not a slash and store in group 2
      /             : a slash
      ([^/\s]+)     : match everything that is not a slash or a space and store in group 3
    ~               : regex delimiter