PHP string functions to find, replace, remove and extract

PHP has a lot of string functions, the ones used in this post are mostly of the str_ variety except there are many ways and options to do the tasks done in these examples. This post consists of handling strings if you need to:

  • Count an occurance of a word.
  • Replace words in a string with another word.
  • Remove parts of the string after a certain character.
  • Extract a part from the string after a certain character.

Replacing a word or match in a string

$mystring = "This is my string. It is 11:08pm";
$remove_word = str_replace("string", "rope", $mystring);//This is my rope. It is 11:08pm

$mystring = "A string that contains naughty words like flog and muppet";
$filter = array("flog", "muppet", "swearword1", "swearword2", "etc");
$filter_string = str_replace($filter, "****", $mystring);//A string that contains naughty words like **** and ****

$mystring = "This is a good string, It is good because i made it.";
$count = str_replace("good", "", $mystring, $count);//2

 

Breaking down a string into an array

$mystring = "My good string, isnt it so good?!";
$array = str_word_count($mystring, 1);
print_r($array);//Array ( [0] => My [1] => good [2] => string [3] => isnt [4] => it [5] => so [6] => good )
echo $array[2];//string

Counting characters in a string

echo strlen("This is the example string"); //26

See if word is in string

$mystring = 'Yes it is another example string!';
$find   = 'string';
$position = strpos($mystring, $find);
if ($position === false) {
    echo "The word '$find' was not found in the string '$mystring'";
} else {
    echo "The word '$find' was found in the string '$mystring' <br>and exists at position $position";
}

Fetching / extracting from string at certain position

$mystring = "This string was made at 11:08:22";
$example = substr($mystring, -8);//11:08:22
$example2 = substr($mystring, -8, 5);//11:08
$mystring2 = "Time: 11:08:22 success";
$example4 = substr($mystring2, -6, -8);//11:08:22
$example4 = substr($mystring2, -6, -11);//11:08

Fetching only after certain character in string

$mystring = "Twitter username @gary_fox";
$username = substr($mystring, strpos($mystring, "@") + 1);
echo $username;//gary_fox
//or
$username = explode('@', $mystring, 2)[1];//gary_fox
//kinda
echo strrchr("Twitter username @gary_fox","@");//@gary_fox

These i in my belief handy and a good range of string handlers for a beginner in PHP. You can do quite a bit with the prebuilt str_ functions, I look forward to making another post going over more string handling and manipulation.