This post covers the Extracting section of the Strings chapter when studying for the Zend PHP 7 Certification.
Some of the string functions for extracting characters in a given string can be seen below.
The substr()
function returns part of a string. It takes three parameters.
echo substr('abcdef', 1); // bcdef
echo substr('abcdef', 1, 3); // bcd
echo substr('abcdef', 0, 4); // abcd
echo substr('abcdef', 0, 8); // abcdef
echo substr('abcdef', -1, 1); // f
The str_word_count()
function returns information about words used in a string. This function also takes three parameters.
$str = 'Hello World, how are you today?';
print_r(str_word_count($str, 0)); // Outputs: 6
print_r(str_word_count($str, 1)); // Outputs: Array ( [0] => Hello [1] => World [2] => how [3] => are [4] => you [5] => today )
print_r(str_word_count($str, 1, '?')); // Outputs: Array ( [0] => Hello [1] => World [2] => how [3] => are [4] => you [5] => today? )
print_r(str_word_count($str, 2)); // Outputs: Array ( [0] => Hello [6] => World [13] => how [17] => are [21] => you [25] => today )
To translate characters or replace substrings, use the strtr()
function. It can take four parameters.
echo strtr("Hilla Warld","ia","eo"); // Outputs: Hello World
$arr = array("Hello" => "Hi", "World" => "Earth");
echo strtr("Hello World",$arr); // Outputs: Hi Earth
Note that strtr()
is case sensitive.
$arr = array("Hello" => "Hi", "World" => "Earth");
echo strtr("Hello world",$arr); // Outputs: Hi world
The strspn()
function finds the length of the initial segment of a string consisting entirely of characters contained within a given mask. strspn()
takes four parameters.
// subject does not start with any characters from mask
var_dump(strspn("foo", "o"));
// examine two characters from subject starting at offset 1
var_dump(strspn("foo", "o", 1, 2));
// examine one character from subject starting at offset 1
var_dump(strspn("foo", "o", 1, 1));
// Outputs:
int(0)
int(2)
int(1)
Using the strtok()
function tokenises a string. It only take two arguments.
$string = "This is\tan example\nstring";
$tok = strtok($string, " \n\t");
while ($tok !== false) {
echo "Word=$tok<br />";
$tok = strtok(" \n\t");
}
// Outputs:
Word=This
Word=is
Word=an
Word=example
Word=string
View the other sections:
Note: This article is based on PHP version 7.1.