Quick PHP string manipulation with strpos and substr

Two handy and complimenting string functions in PHP that assist with string manipulation and any tasks involving breaking down a string.

The first function is strpos which finds the position of the first occurrence in a string for the needle (search term).

strpos

strpos will return false if the needle was not found.

$string = "The quick brown fox jumps over the lazy dog";
echo strpos($string, 'quick');//4

This outputs 4 because the word “quick” begins at the 4th placement in the string. The strpos sequence begins at 0.

Using an offset means the search won’t include any matches before the offset number. Using -1 means the search is reversed.

$string = "The quick brown fox jumps over the lazy dog";
echo strpos($string, 'o');//12

echo strpos($string, 'o', 14);//17

strpos can also be used as a condition if a string contains the needle:

$string = "The quick brown fox jumps over the lazy dog";
$position = strpos($string, 'fox');

if ($position !== false) {
     echo "Found";
} else {
     echo "Not found";
}

substr

Now for the next function which breaks up the string based on position offsets, this function is substr and it will return a part of a string based on the offset and length.

$string = "The quick brown fox jumps over the lazy dog";
echo substr($string, 9);//brown fox jumps over the lazy dog

The offset of 9 means the string gets returned starting from the 9th character.

Leaving the length as null means from the offset to the end of the string will be returned.

$string = "The quick brown fox jumps over the lazy dog";
echo substr($string, 9, 16);//brown fox jumps

A length of 16 has only the next 16 characters being returned starting at the 9th character of the string.

Using a negative offset starts from the end of the string

$string = "The quick brown fox jumps over the lazy dog"; 
echo substr($string, -8);//lazy dog

-8 will return the last eight characters of the string.

Setting length of 4 will return only four characters working to the end from the last 8 characters

$string = "The quick brown fox jumps over the lazy dog"; 
echo substr($string, -8, 4);//lazy

Example

A string breakdown example for when pos strpos and substr are used to find an id:

$string = "03/22 08:52:50 id=[c5ZC0DUV] TRACE  :........router_forward_getOI:         route handle:   7f5251c8"; 
$first_pos = (strpos($string, 'id=[') + 4);
$last_pos = strpos($string, ']');

echo substr($string, $first_pos, 8);//c5ZC0DUV