Preg_split on 2 characters


Preg_split on 2 characters



Im trying to split a string on 2 variables (T & +) which when using on "2018-06-25T10:32:00+01:00" will split it to:-


[0] => 2018-06-25
[1] => 10:32:00
[2] => 01:00



So I thought I could use "preg_split("/ (T|+) /", $ent)", but it itsnt working at all.



My code I have (in PHP) is:-


$ent = "2018-06-25T10:32:00+01:00";
print_r(preg_split("/ (T|+) /", $ent));



Any ideas what Im doing wrong?





Remove the spaces
– Philipp
Jul 2 at 9:43





That worked, thank you :-) Sorry, Im a newbie at this
– Tony Cross
Jul 2 at 9:57





Why do you parse dates using regex? PHP provides the DateTime classes that do the job faster and safer than manual parsing. What is your exact use case?
– axiac
Jul 2 at 10:08



regex


DateTime





Can you please accept the answer if it helped you? :)
– Nimeshka Srimal
Jul 5 at 16:56




3 Answers
3



You have the problem in your regex. You can give it like below;


print_r(preg_split("/T|+/", $ent));



Without using a regex, you can also use the php's Datetime class to split this into date and time (I prefer this).


$ent = '2018-06-25T10:32:00+02:00';
$datetime = new DateTime($ent);

$date = $datetime->format('Y-m-d');
$time = $datetime->format('H:i:s');
$offset = $datetime->getOffset() / 3600;

echo $date.'<br/>';
echo $time.'<br/>';
echo $offset.'<br/>';



Hope it helps!!



Parsing dates in PHP is not the best use case for regex. Maybe it is the best way to handle dates in other languages but not in PHP. PHP provides the DateTime classes that handle the dates faster and safer than manual parsing.


regex


DateTime



This is how your code should look like:


$date = new DateTime("2018-06-25T10:32:00+01:00");

echo $date->format('Y-m-d'), "n";
echo $date->format('H:i:s'), "n";
echo $date->format('P'), "n";



Check out the result: https://3v4l.org/gFvLp



Read more about the DateTime class and DateTime::format().


DateTime


DateTime::format()



For your example you use an alternation with whitespaces (T|+) which have meaning.


(T|+)



What you could do is remove the whitespaces and use (T|+) or as an alternative use a character class [T+]


(T|+)


[T+]


$ent = "2018-06-25T10:32:00+01:00";
print_r(preg_split("/[T+]/", $ent));






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Rothschild family

Cinema of Italy