Here are string functions that do not need a whole lesson each, but you will meet them often.
str_repeat(): repeat text
<?php
echo str_repeat("=", 20) . "\n";
echo str_repeat("Ha", 3);
====================
HaHaHa
str_pad(): pad to a fixed length
<?php
echo str_pad("7", 3, "0", STR_PAD_LEFT) . "\n"; // 007
echo str_pad("Item", 10, ".") . "Price"; // pad on the right by default
007
Item......Price
Zero-padded numbers are handy for invoice numbers.
strrev(): reverse
<?php
echo strrev("PHP");
PHP
That example reads the same both ways. Try strrev("stressed") yourself.
wordwrap(): break long lines
<?php
$text = "PHP is a popular language for building websites";
echo wordwrap($text, 20, "\n", true);
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.
<?php
echo nl2br("Line one\nLine two");
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
<?php
function title(string $text): string
{
return ucwords(strtolower(trim($text)));
}
echo title(" welcome TO my site ");
Welcome To My Site
lcfirst(): lowercase the first letter
<?php
echo lcfirst("HelloWorld");
helloWorld
Other helpers worth knowing
| Function | Use |
|---|---|
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 |