php - 使用正则表达式将行拆分为多个部分
问题描述
我有一个字符串
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]
值,但不确定如何拆分它以获取其他值。
解决方案
尝试使用 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"
推荐阅读
- celery - 芹菜任务永久启动(未重试)
- python - 两个 sublot 的 Python 动画
- python - Python中的数组声明问题
- flutter - Flutter - 如何在水平 ListView 中获取 FlatButton 的宽度
- javascript - 在会话期间使用 react 存储用户数据的最佳方法是什么?
- geocoding - 使用经度和纬度与 OpenRefine 进行地理数据协调
- android - 协程异常抛出 KotlinNullPointerException
- node.js - 使用 Node/Axios 从 OneDrive API 下载二进制文件
- java - 获取更多 SSL 调试信息
- azure - Azure 中所有存储帐户的文件共享列表