多重爆炸

Multiple Explode

我有一个来自 excel 的列,其中包含以下示例文本,我想在分隔符中分解它。这是示例

'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'

我需要它用 x 展开,我只需要第一个 x 之后的数字,即上面的 17、18、19 或 20。我确实喜欢以下内容:

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

它给了我 17 / 1、18 / 2 等等,但在这种情况下我只需要 17 或 18

如果谁有好的解决办法请写在这里

您可以使用preg_match提取第一个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";
}

输出:

17
18
19
20

Demo on 3v4l.org

如果只想使用 explode,只需在 x 上展开后在 space 上展开并取第一个值:

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

Demo on 3v4l.org