agyanadda@gmail.com

PHP String Functions

Strings and Numbers 1 min read Updated Dec 1, 2026 Topic 8 of 36
Function Example Result
strlen() strlen('Hello') 5
strtoupper() / strtolower() strtoupper('php') 'PHP'
ucfirst() / ucwords() ucwords('asha kumari') 'Asha Kumari'
trim() trim(' hi ') 'hi'
str_replace() str_replace('-', ' ', 'a-b') 'a b'
str_contains() (PHP 8) str_contains('hello', 'ell') true
str_starts_with() str_starts_with($url, 'https') true
strpos() strpos('hello', 'l') 2
substr() substr('Laravel', 0, 4) 'Lara'
explode() explode(',', 'a,b,c') ['a','b','c']
implode() implode(', ', $arr) 'a, b, c'
str_pad() str_pad('7', 3, '0', STR_PAD_LEFT) '007'
number_format() number_format(1234.5, 2) '1,234.50'

Hindi and emojis

For non-English text use the mb_ versions: mb_strlen(), mb_substr(), mb_strtoupper(). They count characters correctly.

Example

Example — Clean user input and create a slug PHP
<?php
$input = '   learn PHP string functions   ';
$clean = trim($input);

echo ucwords($clean) . '<br>';
echo 'Length: ' . strlen($clean) . '<br>';
echo 'Has "PHP": ' . (str_contains($clean, 'PHP') ? 'yes' : 'no') . '<br>';

$slug = strtolower(str_replace(' ', '-', $clean));
echo "Slug: $slug<br>";

$tags = explode(',', 'php,mysql,laravel');
echo 'Tags: ' . implode(' | ', $tags) . '<br>';
echo 'Roll no: ' . str_pad('42', 5, '0', STR_PAD_LEFT);

Output: Learn PHP String Functions / Length: 26 / Has "PHP": yes / Slug: learn-php-string-functions / Tags: php | mysql | laravel / Roll no: 00042

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function splits a string into an array?

Exercise 2 True / False

mb_strlen() counts Hindi characters correctly.

Exercise 3 Fill in the Blank

___() removes spaces from both ends of a string.

Frequently Asked Questions

0 means 'found at position 0', which is falsy. Compare strictly: if (strpos($s, 'x') !== false), or use str_contains() in PHP 8.