php preg_split w/regex
<?php
$str = '17:30 Football 18:30 Meal 20:00 Quiet';
$chars = preg_split('/^([0-1][0-9]|[2][0-3]):([0-5][0-9])$/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r ($chars);
?>
returned:
Array (
[0] => Array (
[0] => 17:30 Football 18:30 Meal 20:00 Quiet
[1] => 0
)
)
while I was hoping for:
Array (
[0] => Array (
[0] => Football
[开发者_JAVA百科1] => 7
)
[1] => Array (
[0] => Meal
[1] => 22
)
etc.
What can I do?
You need to drop the anchors ^
and $
around your regex - with them in place the regex can never match as they require the splitting string to begin at the start of the string and to end at the end of the string - this can never be true unless your input is 17:30
only.
You might also want to include space characters in your regex, like
$chars = preg_split('/\s*([0-1][0-9]|2[0-3]):([0-5][0-9])\s*/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
In regular expressions the ^
and $
symbols are anchors to the beginning and end, respectively, of the line of text you are scanning. Try removing them from your pattern. Maybe try something like:
<?php $str = '17:30 Football 18:30 Meal 20:00 Quiet'; $chars = preg_split('/(?:[01]\d|2[0-3]):(?:[0-5]\d)/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE); print_r ($chars); ?>
Don't forget that :
is a special character in regular expressions so it will need to be escaped.
By default all bracketed groups are remembered, but you can stop this with the ?:
syntax. I'm not entirely sure if that will cause an issue in PHP because I tested the expression with Python, but it should prevent the matches from being returned in the array.
You may also want to extend the expression slightly to automatically strip out the whitespace around your words:
$chars = preg_split('/\s*(?:[01]\d|2[0-3]):(?:[0-5]\d)\s*/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
Hope this helps!
Or:
$chars = preg_split('/\b[0-9:\s]{6,7}\b/', $str,-1,PREG_SPLIT_OFFSET_CAPTURE);
This removes the leading space.
精彩评论