Here are some examples:
Some text A
Some text A 8:00-19:00
8:00-19:00
Some text A 8:00-19:00 Some text B
For each case described above, I need to capture (if possible):
8:00-19:00
)Some text A
)Some text B
)With this pattern #^(.*?) ?(\d{1,2}:\d{2}-\d{1,2}:\d{2})?$#
, I can capture (from example 2):
Some text A
8:00-19:00
But I can't capture the rest of the line by adding (.*)
or (.*?)
at the end of the pattern.
Can you help me? Thank you!
I think your main problem is that you've made the group of digits optional by adding ?
after it (which I don't think you want).
This works for me /^(.*) ?(\d{1,2}:\d{2}-\d{1,2}:\d{2}) ?(.*)$/
:
<?
$str = "Some text A 8:00-19:00 Some text B";
$pat = "/^(.*) ?(\d{1,2}:\d{2}-\d{1,2}:\d{2}) ?(.*)$/";
if(preg_match($pat, $str, $matches)){
/*
Cases 2, 3 and 4
Array
(
[0] => Some text A 8:00-19:00 Some text B
[1] => Some text A
[2] => 8:00-19:00
[3] => Some text B
)
*/
}else{
/* Case 1 */
}
?>
<?php
$pattern = <<<REGEX
/
(?:
(.*)?\s* #Prefix with trailing spaces
(
(?:\d{1,2}:\d{1,2}-?) #(dd:dd)-?
{2} #2 of those
) #(The time)
\s*(.*) #Trailing spaces and suffix
|
([a-zA-Z ]+) #Either that, or just text with spaces
)
/x
REGEX;
preg_match($pattern, "Some text A 8:00-19:00 Some text B", $matches);
print_r($matches);
The array $matches
will contain all the parts you need.
Edit: Now matches just text as well.
OK... I don't understand exactly what are the case scenarios.
I believe you want to match 3 optional groups (which will probably match "malformed" input, unless you provide case scenarios you DON'T want to match).
This works in all for examples, although in case 1, "Some text A" appears in $matches[0] and $matches[3] instead of $matches[1].
/^([A-Za-z ]*?)([0-2]{0,1}[0-9]\:[0-6][0-9]\-[0-2]{0,1}[0-9]\:[0-6][0-9])?([A-Za-z ]*?)$/
How about using preg_split ?
$tests = array(
'Some text A',
'Some text A 8:00-19:00',
'8:00-19:00',
'Some text A 8:00-19:00 Some text B'
);
foreach ($tests as $test) {
$res = preg_split('/(\d\d?:\d\d-\d\d?:\d\d)/', $test, -1,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
print_r($res);
}
output:
Array
(
[0] => Some text A
)
Array
(
[0] => Some text A
[1] => 8:00-19:00
)
Array
(
[0] => 8:00-19:00
)
Array
(
[0] => Some text A
[1] => 8:00-19:00
[2] => Some text B
)