这里最简单的做法是编写一个正则表达式来捕获文本,然后解析捕获的内容以查看您得到的内容。首先,假设您有测试平台:
$tests = array(
'Genesis 1:1' => 'Genesis Chapter 1, Verse 1',
'1 Kings 2:5' => '1 Kings Chapter 2, Verse 5',
'Job 3' => 'Job Chapter 3',
'Romans 8:1-7' => 'Romans Chapter 8, Verses 1 to 7',
'1 John 5:6-11' => '1 John Chapter 5, Verses 6 to 11'
);
所以,你有,从左到右:
- 书名,可选前缀为数字
- 章号
- 节数,可选,可选后跟一个范围。
因此,我们可以编写一个正则表达式来匹配所有这些情况:
((?:\d+\s)?\w+)\s+(\d+)(?::(\d+(?:-\d+)?))?
现在看看我们从正则表达式中得到了什么:
foreach( $tests as $test => $answer) {
// Match the regex against the test case
preg_match( $regex, $test, $match);
// Ignore the first entry, the 2nd and 3rd entries hold the book and chapter
list( , $book, $chapter) = array_map( 'trim', $match);
$output = "$book Chapter $chapter";
// If the fourth match exists, we have a verse entry
if( isset( $match[3])) {
// If there is no dash, it's a single verse
if( strpos( $match[3], '-') === false) {
$output .= ", Verse " . $match[3];
} else {
// Otherwise it's a range of verses
list( $start, $end) = explode( '-', $match[3]);
$output .= ", Verses $start to $end";
}
}
// Here $output matches the value in $answer from our test cases
echo $answer . "\n" . $output . "\n\n";
}
您可以在此演示中看到它的工作原理。