Reputation: 346
I have the following string:
John 1:9
and the following php code:
$parts = preg_split('/[^a-z]/i', $a,2);
var_dump($parts);
It returns the following result (as i expect)
array (size=2)
0 => string 'John' (length=4)
1 => string '1:9' (length=3)
However, i might want the book "1 John 1:9" and it doesn't work to detect "1 John". How do i need to change the regex code to accept numbers 1-4 and a space before the book name?
Upvotes: 0
Views: 115
Reputation: 5846
I think the easiest way is to check if the first result is numeric and if so join the first two keys.
$parts = preg_split('/[^a-z]/i', $a);
if (is_numeric($parts[0])) {
$parts[0] = array_shift($parts) . ' ' . $parts[0];
}
var_dump($parts);
Upvotes: 0
Reputation: 2894
Rather than just splitting then you'll need to write a regex to match each part.
You could use something like:
/^((?:[1-4] )?[a-z]+) ([\d:]*)$/
Then you'd use preg_match
as follows:
preg_match('/^((?:[1-4] )?[a-z]+) ([\d:]*)$/', $string, $parts);
Upvotes: 1
Reputation: 91375
How about:
preg_match('/^((?:\d{1,4} )?\S+) (.+)$/', $string, $matches);
The book name (with optional number) is in $matches[1]
and the rest in $matches[2]
Upvotes: 1