I have this sentence:
17:20 - Fermata d’autobus 19:05 - La musica che non ti ho detto 21:00 - Quando l'amore brucia l'anima - Walk the Line 23:30 - Maximum Risk 01:15 - Cash Game 04:15 - Cash Game2
I want to split the phrase into content arrays:
[0] 21:00 - Quando l'amore brucia l'anima - Walk the Line
[1] 23:30 - Maximum Risk
[2] 01:15 - Cash Game
therefore with these elements only. I tried it that way:
$tt1="17:20 - Fermata d’autobus 19:05 - La musica che non ti ho detto 21:00 - Quando l'amore brucia l'anima - Walk the Line 23:30 - Maximum Risk 01:15 - Cash Game 04:15 - Cash Game2";
$arr1 = preg_split("/((2[0-3])|(0[0-3])):[0-9]*/",$tt1, -1);
foreach( array_keys($arr1) as $k ){
$v = $arr1[$k];
echo $v."</br>";
}
However, that is what I see in the print:
17:20 - Fermata d’autobus 19:05 - La musica che non ti ho detto
- Quando l'amore brucia l'anima - Walk the Line
- Maximum Risk
- Cash Game 04:15 - Cash Game2
I would like the array to contain just that:
21:00 - Quando l'amore brucia l'anima - Walk the Line
23:30 - Maximum Risk
01:15 - Cash Game
How can I change the code for that output?
I don't think preg_split
is the best way to do it. I'm sure there is a complicated preg_match
pattern which can do this. If you want to use preg_split
, you have to split the phrase by every time (not just 20pm to 03pm), and filter out those which you want in PHP.. Like this for example:
$tt1="17:20 - Fermata d’autobus 19:05 - La musica che non ti ho detto 21:00 - Quando l'amore brucia l'anima - Walk the Line 23:30 - Maximum Risk 01:15 - Cash Game 04:15 - Cash Game2";
// first, split the string by the time format XX:XX, preserving the delimiters
$arr1 = array_filter(preg_split("/([0-9]{2}:[0-9]{2})/", $tt1, -1, PREG_SPLIT_DELIM_CAPTURE));
// after that, split the result into two arrays, first one contains the times, second the phrases
$odd = $even = [];
$both = [&$even, &$odd];
array_walk($arr1, function($v, $k) use ($both) { $both[$k % 2][] = $v; });
// after that, combine the two arrays into a third one, where the keys will be the times, and values the phrases
foreach(array_combine($odd, $even) as $key => $value){
list($hours, $minutes) = explode(':', $key);
// explode the time so you can check the hours from 20pm to 3am
if (intval($hours) >= 20 || intval($hours) <= 3) {
// and output the time with the corresponding phrase
echo $key . $value . "<br>";
}
}
I see you have already been answered, but here's a solution with only one array:
$re = '/(.*?)(\d{1,2}:\d{2}|$)/';
$result = [];
$matches = preg_split($re, $tt1, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
for ($i = 0; $i < count($matches) - 1; $i += 2) {
$hour = (int) $matches[$i];
if ($hour >= 20 || $hour <= 3)
$result[] = $matches[$i] . $matches[$i + 1];
}
print_r($result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.