Skip to content

PHP Tutorial Strings

More Useful String Functions

Lesson 68 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

Here are string functions that do not need a whole lesson each, but you will meet them often.

str_repeat(): repeat text

index.php
PHP
<?php
echo str_repeat("=", 20) . "\n";
echo str_repeat("Ha", 3);
Output
OUTPUT
====================
HaHaHa

str_pad(): pad to a fixed length

index.php
PHP
<?php
echo str_pad("7", 3, "0", STR_PAD_LEFT) . "\n";   // 007
echo str_pad("Item", 10, ".") . "Price";          // pad on the right by default
Output
OUTPUT
007
Item......Price

Zero-padded numbers are handy for invoice numbers.

strrev(): reverse

index.php
PHP
<?php
echo strrev("PHP");
Output
OUTPUT
PHP

That example reads the same both ways. Try strrev("stressed") yourself.

wordwrap(): break long lines

index.php
PHP
<?php
$text = "PHP is a popular language for building websites";

echo wordwrap($text, 20, "\n", true);
Output
OUTPUT
PHP is a popular
language for
building websites

nl2br(): new lines to HTML

A browser ignores a plain new line. nl2br() adds <br> tags so the lines show up.

index.php
PHP
<?php
echo nl2br("Line one\nLine two");
Output
OUTPUT
Line one<br />
Line two

strcmp(): compare two strings

It returns a negative number, zero or a positive number. Comparing Strings explains it.

ucfirst plus lowercase: a title helper

index.php
PHP
<?php
function title(string $text): string
{
    return ucwords(strtolower(trim($text)));
}

echo title("  welcome TO my site ");
Output
OUTPUT
Welcome To My Site

lcfirst(): lowercase the first letter

index.php
PHP
<?php
echo lcfirst("HelloWorld");
Output
OUTPUT
helloWorld

Other helpers worth knowing

FunctionUse
strlen()Length in bytes
strtolower() / strtoupper()Change case
str_word_count()Count words
similar_text()How alike two strings are
htmlspecialchars()Make text safe for HTML
strip_tags()Remove HTML tags
addslashes()Escape quotes (not for SQL, use prepared statements)
md5() / sha1()Old hashes, not for passwords
dangerous
Do not use md5() or sha1() for passwords
They are fast, which makes them easy to crack. password_hash() is the right tool.