Skip to content
PHP Logo

What are the advantages of using substr() function over regular expressions for date manipulation in PHP?

When manipulating dates in PHP, using the substr() function can be advantageous over regular expressions because it is simpler and more efficient for extracting specific parts of a date string, such as the year, month, or day. Regular expressions can be complex and harder to read, especially for beginners. Additionally, substr() is a built-in PHP function, so there is no need to rely on external libraries for date manipulation.

php
$date = "2022-10-15";
$year = substr($date, 0, 4);
$month = substr($date, 5, 2);
$day = substr($date, 8, 2);

echo "Year: $year, Month: $month, Day: $day";