首页 > 解决方案 > 使用正则表达式将行拆分为多个部分

问题描述

我有一个字符串

BK0001 My book (4th Edition) $49.95 (Clearance Price!)

我想要一种方法把它分成不同的部分,比如

[BK0001] 
[My Book (4th Edition)] 
[$49.95] 
[(Clearance Price!)]

我对正则表达式很陌生,我正在使用它来解析文件上的一行。我设法BK0001通过使用获得第一部分

$parts = preg_split('/\s+/', 'BK0001 My book (4th Edition) $49.95 (Clearance Price!)';

然后获取$part[0]值,但不确定如何拆分它以获取其他值。

标签: phpregexsplitpreg-split

解决方案


尝试使用 preg_match

$book_text = "BK0001 My book (4th Edition) $49.95 (Clearance Price!)";
if(preg_match("/([\w\d]+)\s+(.*?)\s+\\((.*?)\\)\s+(\\$[\d\.]+)\s+\\((.*?)\\)$/",$book_text,$matches)) {
    //Write code here
    print_r($matches);
}

$matches[0] 保留用于完整匹配字符串。您可以从 $matches[1] 中找到拆分部分...

Array ( [0] => BK0001 My book (4th Edition) $49.95 (Clearance Price!) [1] => BK0001 [2] => My book [3] => 4th Edition [4] => $49.95 [5] => Clearance Price! )

$matches[1] is "book number"
$matches[2] is "book name"
$matches[3] is "edition"
$matches[4] is "price"
$matches[5] is "special text"

推荐阅读