Strings, dates and JSON
Web apps spend their days handling text: cleaning form input, formatting prices and dates, building URLs, and sending JSON to front ends and mobile apps. PHP has a function for nearly every one of these jobs. This lesson covers the ones you'll use constantly, and the traps (like multi-byte text and time zones) that catch people out.
Everyday string functions
⚠️
strposreturns0when the text is at the start, and0is falsy. Always compare with!== false, or usestr_contains,str_starts_withandstr_ends_with.
Multi-byte text
strlen and substr count bytes. Characters outside plain English take 2–4 bytes in UTF-8, so use the mb_ functions for user text:
Formatting numbers and text
Regular expressions
The preg_ functions use Perl-compatible regular expressions:
| Function | Does |
|---|---|
preg_match($re, $s, $m) |
First match → 1/0, groups in $m |
preg_match_all |
Every match |
preg_replace($re, $with, $s) |
Replace |
preg_split($re, $s) |
Split on a pattern |
For validating common formats, prefer filter_var (see Forms, requests and sessions) over hand-written patterns.
Dates and times
Use the DateTimeImmutable class: its methods return new objects instead of changing the original, which avoids a whole family of bugs.
| Format | Gives |
|---|---|
Y-m-d |
2026-11-22 |
H:i:s |
10:30:00 (24-hour) |
g:i A |
10:30 AM |
D / l |
Sun / Sunday |
M / F |
Nov / November |
jS |
22nd |
DATE_ATOM |
2026-11-22T10:30:00+05:30 (ISO 8601) |
💡 Store dates in UTC in databases, and convert to the user's time zone only when displaying.
new DateTimeImmutable('now')uses the server's default time zone (date_default_timezone_setorphp.ini), so be explicit.
Parsing dates safely
Check user-entered dates with checkdate or the parser's warnings: invalid dates are "corrected" instead of rejected.
JSON
JSON is how PHP talks to JavaScript front ends, mobile apps and other APIs:
Invalid JSON
json_decode returns null on bad input by default, which can't be told apart from a real null. Use JSON_THROW_ON_ERROR:
Practice
- Turn
" Hello, PHP World! "into the slughello-php-world. - Print today's date in three formats:
2026-11-22,Sunday 22 Novemberand ISO 8601. - Calculate someone's age in years from a birth date string with
diff. - Decode
{"products":[{"name":"Pen","price":1.5},{"name":"Pad","price":4}]}and print the total price.
1.Why can if (strpos($s, "The")) fail when $s starts with "The"?
2.Which function counts the characters (not bytes) of "नमस्ते"?
3.Why prefer DateTimeImmutable over DateTime?
4.How do you get an exception for invalid JSON?