PHP Introduction | Text and Date Manipulation | Main Functions for Handling Text

When creating programs, one thing that is surprisingly important is knowing how to manipulate different values. Without that knowledge, many small problems become difficult. First, let us introduce the main functions used to manipulate text.

Get the Length of Text

$variable = strlen(text);
$variable = mb_strlen(text);

These functions find out how many characters are in the text. strlen returns an integer for ordinary English text, or alphanumeric single-byte characters. mb_strlen checks characters that are not single-byte, such as Korean, and returns the character count as an integer.

$n = strlen('hello'); // $n becomes 5.

Look Up the Position of Text

$variable = strpos(target text, search text, start position);
$variable = mb_strpos(target text, search text, start position, encoding);

These functions find the position of text you want to search for inside another text. Here again, two types are provided: strpos for single-byte characters and mb_strpos for other characters.

The first argument specifies the target text to search, and the second specifies the text to search for. These two are required. The third specifies, as a number, from which character to start searching. The fourth specifies the text encoding.

For alphanumeric searches with strpos, calling it with only the first two arguments will usually be enough. For mb_strpos, when searching Korean or similar text, assume that specifying all four arguments is the basic approach. In particular, if the fourth encoding argument is not specified correctly, the search may not work properly.

The return value is an integer indicating which character position was found, with the first character being 0. If the text is not found, false is returned.

$n = strpos("Hello","e",0,"UTF-8"); // $n becomes 1.

Extract Part of Text

$variable = substr(text, start position, length);
$variable = mb_substr(text, start position, length, encoding);

These functions return the specified part of a text. For example, use them when you want to extract only "PHP" from the text "Hello PHP World".

The first argument specifies the original text to extract from, while the second and third specify the position and number of characters to extract. Positions start from 0. For Korean and similar text, always specify the encoding when using mb_substr.

$s = substr("Hello",2,2); // $s becomes "ll".

Replace Text

$variable = str_replace(search text, replacement text, text);

For text replacement, PHP provides the convenient str_replace function. You only need to specify the search text, the replacement text, and the target text, and the replaced text is returned. There is no separate function for Korean; this one function handles the operation.

This function returns the third text after replacing all occurrences of the search text with the replacement text.

$s = str_replace("java","PHP","Hello java!"); // $s becomes "Hello PHP!".