我有一个类似
的字符串BK0001 My book (4th Edition) $49.95 (Clearance Price!)
我想要一种将其拆分为不同部分的方法,例如
[BK0001]
[My Book (4th Edition)]
[$49.95]
[(Clearance Price!)]
我在regex上还很新,我正在用它来解析文件上的一行。我设法通过使用
获得了第一部分BK0001
$parts = preg_split('/\s+/', 'BK0001 My book (4th Edition) $49.95 (Clearance Price!)';
然后获取$part[0]
值,但不确定如何将其拆分以获取其他值。
答案 0 :(得分:3)
您可以使用带有捕获组的单个模式来匹配输入字符串的特定部分:
preg_match('~^(?<code>\S+)\s+(?<name>.*?)\s+(?<num>\$\d[\d.]*)\s*(?<details>.*)$~', $text, $matches)
请参见regex demo。实际上,最后一个$
不是必需的,它只是表明整个字符串都已匹配。
详细信息
^
-字符串的开头(?<code>\S+)
-组“代码”:一个或多个非空白字符\s+
-超过1个空格(?<name>.*?)
-组“名称”:除换行符以外的任何0+个字符,并且尽可能少\s+
-超过1个空格(?<num>\$\d[\d.]*)
-组“ num”:一个$
,然后是1位数字,然后是0+位数字,或者是.
\s*
-超过0个空格(?<details>.*)
-组“明细”:除换行符以外的任何0+个字符,并且尽可能多$
-字符串的结尾。$re = '~^(?<code>\S+)\s+(?<name>.*?)\s+(?<num>\$\d[\d.]*)\s*(?<details>.*)$~';
$str = 'BK0001 My book (4th Edition) $49.95 (Clearance Price!)';
if (preg_match($re, $str, $m)) {
echo "Code: " . $m["code"] . "\nName: " . $m["name"] . "\nPrice: " .
$m["num"] . "\nDetails: " . $m["details"];
}
输出:
Code: BK0001
Name: My book (4th Edition)
Price: $49.95
Details: (Clearance Price!)
答案 1 :(得分:3)
尝试使用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"