Search code examples
phpexplode

Multiple Explode


I have a column from excel with the following sample text coming in, and I want to explode it in delimiter. Here is the sample

'ABC 11.0x17 / 1x4 / 2x4 XYZ'
'ABC 12.1x18 / 2x4 3x4 XYZ'
'ABC DEF 12.1x19 / 3x4 4x4 XYZ'
'ABC DEF GHI A1 13x20 / 3x4 / 4x4 XYZ'

and I need it to be exploded with x and I need only number that is after 1st x which would be 17, 18, 19 or 20 from the above. I did like the following:

$text   = explode('x', $row[6]);
echo $text[1]; 

It gives me 17 / 1, 18 / 2 and so on but I just need 17 or 18 in this case

If anybody have a good solution please write here.


Solution

  • You can use preg_match to extract the digits after the first x:

    $strings = array(
        'ABC 11.0x17 / 1x4 2x4 XYZ',
        'ABC 12.1x18 / 2x4 3x4 XYZ',
        'ABC DEF 12.1x19 / 3x4 4x4 XYZ',
        'ABC DEF GHI A1 13x20 / 3x4 4x4 XYZ'
    );
    
    foreach ($strings as $str) {
        preg_match('/^[^x]+x(\d+)/', $str, $matches);
        echo $matches[1] . "\n";
    }
    

    Output:

    17
    18
    19
    20
    

    Demo on 3v4l.org

    If you want to use only explode, just explode on space after exploding on x and take the first value:

    foreach ($strings as $str) {
        $text = explode('x', $str, 2);
        $text = explode(' ', $text[1]);
        echo "$text[0]\n";
    }
    

    Demo on 3v4l.org