任何人都可以帮助我如何将诗歌格式拆分/分解为3个部分吗?
条件应如下。
第二部分和第三部分必须用冒号分隔。例如在Gen 1:1
中它必须分开为
[0] = Gen
[1] = 1
[2] = 1
它由一个空格(或许多空间使其用户友好)和冒号
分隔其次,在前面有数字的经文中是一个问题,因为用户可以将其键入为
1 Cor 1:1,他们也可以输入1Cor 1:1
在任何一种情况下我都希望[1]和[2]用冒号分割,其余部分将被修剪所有空格并成为[0]值。
这可能吗?因为我正在考虑只使用一个文本框来搜索诗歌,而php会在将其作为查询传递之前对其进行相应的验证。由于
答案 0 :(得分:1)
我想出了以下似乎有用的模式。试试这个:
<?php
$string = '7 Genesis 16:23';
if (preg_match('/^(.*?)\s+(\d+):(\d+)$/', $string, $match)) {
echo "You selected book {$match[1]}, chapter {$match[2]}, verse {$match[3]}!";
} else {
echo "I couldn't understand your input. Please use 'Book chapter:verse' format.";
}
表达式(.*?)
的第一部分与书,(1 Cor)或(Cor)匹配,因此您可能需要/想要对该部分进行额外验证或对其进行优化,但这对于我。希望能让你开始。
答案 1 :(得分:0)
尝试这样的事情:
$str = 'Gen 1:1'; // OR: $str = '1 Cor 1:1';
$array = explode( ' ', $str);
$last = end( $array);
$array = array_merge( array_slice( $array, 0, count( $array) - 1), explode( ':', $last));
var_dump( $array);
答案 2 :(得分:0)
这种模式应该有效:
$subject = <<verse here>>;
$pattern = '/^([0-9a-zA-Z ]+) ([0-9]+):([0-9]+)/';
preg_match($pattern, $subject, $matches);
print_r($matches);
请注意$matches
中的第一个元素将是完整的$ subject。元素1-3将映射到您的元素0-2。
答案 3 :(得分:0)
所以听起来你想要以下内容,按顺序:
(.*)
[ ]+
([0-9]+)
:
([0-9]+)
因此,你的正则表达式看起来像这样:
/^(.*)[ ]*([0-9])+:([0-9]+)$/
运行之后:
$m = '1 Cor 3:14';
$matches = array();
preg_match("/^(.*)[ ]*([0-9])+:([0-9]+)$/", $m, $matches);
$matches
将如下所示:
Array
(
[0] => 1 Cor 3:14
[1] => 1 Cor
[2] => 3
[3] => 14
)