Working with strings
Almost everything a web application does manipulates text: names, emails, titles, URLs, messages. That is why string functions are among the most used in PHP. In this lesson we see how to measure, search, cut and transform text. An important warning from the start: PHP works with bytes. A letter such as ñ or a vowel with an accent takes more than one byte in UTF-8, so the classic functions can give odd results with accented text.
Measuring, searching and extracting
strlen returns the number of bytes and mb_strlen the number of real characters. To search, since PHP 8 there are str_contains, str_starts_with and str_ends_with, which return true or false and are very readable. strpos returns the position of the first occurrence or false if it does not exist; that is why you must compare it with === false, since position 0 is also a valid value. substr cuts a piece given a start and a length.
<?php
$text = 'Learning PHP is fun';
echo strlen($text) . "\n"; // 19
var_dump(str_contains($text, 'PHP')); // bool(true)
var_dump(str_starts_with($text, 'Learn')); // bool(true)
var_dump(str_ends_with($text, 'boring')); // bool(false)
$pos = strpos($text, 'PHP');
echo $pos . "\n"; // 9
echo substr($text, 9, 3) . "\n"; // PHP
echo substr($text, -3) . "\n"; // fun
// The trap with strpos at position 0
if (strpos($text, 'Learning') !== false) {
echo "found\n";
}
$word = 'canción';
echo strlen($word) . ' vs ' . mb_strlen($word) . "\n"; // 8 vs 7Transforming text
strtolower and strtoupper switch between lowercase and uppercase; for accented text use mb_strtolower and mb_strtoupper. ucfirst capitalizes the first letter and ucwords that of each word. trim removes spaces (and line breaks) at the start and end, essential with data typed by a person. str_replace replaces all occurrences of a text with another. str_pad fills up to a length and str_repeat repeats a text.
<?php
$raw = ' ana MARIA lopez ';
$clean = trim($raw);
echo '[' . $clean . "]\n"; // [ana MARIA lopez]
echo ucwords(strtolower($clean)) . "\n"; // Ana Maria Lopez
echo str_replace(' ', '-', strtolower($clean)) . "\n"; // ana-maria-lopez
echo str_pad('7', 3, '0', STR_PAD_LEFT) . "\n"; // 007
echo str_repeat('=', 20) . "\n";
// Build a slug from a title
$title = 'My First Blog Post';
$slug = strtolower(preg_replace('/\s+/', '-', trim($title)));
echo $slug . "\n"; // my-first-blog-postSplitting and joining
explode splits a text into an array using a separator, and implode does the opposite: it joins the elements of an array with a glue. It is the basis for reading comma-separated lists, paths or tags. With str_word_count or explode you can count words. Remember the argument order: explode takes the separator first and then the text.
<?php
$csv = 'php,sql,html,css';
$tags = explode(',', $csv);
print_r($tags); // [php, sql, html, css]
echo implode(' | ', $tags) . "\n"; // php | sql | html | css
echo count($tags) . " tags\n";
// Access characters and compare text
$word = 'level';
echo $word[0] . "\n"; // l
echo strrev($word) === $word ? "palindrome\n" : "not palindrome\n";
// Safe length and cutting with multibyte text
$name = 'José Ñandú';
echo mb_strtoupper($name) . ' (' . mb_strlen($name) . ")\n";
echo mb_substr($name, 0, 4) . "\n"; // JoséFrequent mistakes: using strlen with accents and getting a number larger than expected; forgetting that text functions return a new value instead of changing the variable (you must reassign: $name = trim($name)); and comparing the output of strpos with == instead of ===. To compare texts ignoring case use strcasecmp or convert both to lowercase first.
✎ 我的笔记
仅保存在此浏览器中。登录后可保存到账号。0/5000 字符