Php

String and Date Functions

String Functions in PHP

String functions help you manipulate, analyze, and transform text.


Common String Functions

Function Description
strlen($str) Returns the length of a string
strtoupper($str) Converts to uppercase
strtolower($str) Converts to lowercase
substr($str, start, length) Extracts part of a string
strpos($str, $search) Finds position of substring
str_replace($search, $replace, $subject) Replaces text
trim($str) Removes whitespace from both ends
explode($delimiter, $string) Splits string into an array
implode($glue, $array) Joins array into string

✅ String Examples:

php
$text = " Hello, PHP World! ";

echo strlen($text); // 18
echo strtoupper($text); // " HELLO, PHP WORLD! "
echo substr($text, 7, 3); // "PHP"
echo str_replace("PHP", "JavaScript", $text); // " Hello, JavaScript World! "
echo trim($text); // "Hello, PHP World!"


Date and Time Functions in PHP

Date/time functions allow you to format, calculate, and manipulate dates and times.


Common Date Functions

Function Description
date($format) Returns formatted date/time string
time() Current Unix timestamp (seconds since 1970)
strtotime($string) Converts string into Unix timestamp
mktime(hour, min, sec, month, day, year) Custom timestamp
date_default_timezone_set() Sets time zone

✅ Date Examples:

php
echo date("Y-m-d"); // Current date: e.g. 2025-08-02
echo date("l, h:i A"); // Output: Saturday, 04:30 PM

$timestamp = strtotime("next Monday");
echo date("Y-m-d", $timestamp); // Output: Next Monday's date

// Set a timezone
date_default_timezone_set("Asia/Kolkata");
echo date("h:i A"); // Output in IST


Common date() Format Characters

Character Meaning Example
Y Full year 2025
m Month (2-digit) 08
d Day (2-digit) 02
H Hour (24-hr) 16
h Hour (12-hr) 04
i Minutes 30
A AM/PM PM
l (L) Full weekday name Saturday

Quick Use Case: Timestamp Difference

php
$start = strtotime("2025-08-01");
$end = strtotime("2025-08-10");

$diff = $end - $start;
$days = $diff / (60 * 60 * 24);

echo "Difference: $days days"; // Output: Difference: 9 days

Leave a Reply

Your email address will not be published. Required fields are marked *