Reputation: 793
Can anyone help me how to split /explode verse format to 3 parts?
The condition should be as follows.
the second and 3rd part must be seperated by a colon. so for example in Gen 1:1
it must be seperated as
[0] = Gen
[1] = 1
[2] = 1
it is delimited by a space (or many space to make it user friendly) and by a colon
secondly, in verses with numeric in front is a problem because user can type it as
1 Cor 1:1 and they can also type it as 1Cor 1:1
in either case I want [1] and [2] to be split by a colon and the remaining parts will be trimmed all space and became the [0] value.
is this possible? Because I am thinking of using only one text box for searching of verse and php will validate it accordingly before passing it as query.
Thanks
Upvotes: 0
Views: 1709
Reputation: 59709
Try something like this:
$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);
Upvotes: 0
Reputation: 11142
So it sounds like you want the following, in order:
(.*)
[ ]+
([0-9]+)
:
([0-9]+)
Therefore, your regex would look like so:
/^(.*)[ ]*([0-9])+:([0-9]+)$/
After running this:
$m = '1 Cor 3:14';
$matches = array();
preg_match("/^(.*)[ ]*([0-9])+:([0-9]+)$/", $m, $matches);
$matches
will look like this:
Array
(
[0] => 1 Cor 3:14
[1] => 1 Cor
[2] => 3
[3] => 14
)
Upvotes: 0
Reputation: 468
This pattern should work:
$subject = <<verse here>>;
$pattern = '/^([0-9a-zA-Z ]+) ([0-9]+):([0-9]+)/';
preg_match($pattern, $subject, $matches);
print_r($matches);
Note that the first element in $matches
will be the full $subject. Elements 1-3 will map to your elements 0-2.
Upvotes: 0
Reputation: 69967
I came up with the following pattern that seems to work. Try this:
<?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.";
}
The first part of the expression (.*?)
matches the book, (1 Cor) or just (Cor), so you may need/want to do additional validation on that part or refine it, but this worked okay for me. Hopefully gets you started.
Upvotes: 1