So we have substr and strlen PHP functions covered now – however there is alot more PHP can do out-the-box with strings. Let’s say we are storing the users full name within our database in a single column in the following format firstName-lastName. However on our frontend we want to be able to echo out the first and last name separately. This is where the
strpos function comes into play. This function allows us to look for a specific character within a string and find its position. So in our case we could find the position of the dash within our full name and then make use of the
substr function we previously learned to split the name up into two separate variables.
<?php $fullName = "Michael-Boguslavskiy"; $dashPlace = strpos($fullName, "-"); $firstName = substr($fullName, 0, $dashPlace); $lastName = substr($fullName, $dashPlace + 1); echo $firstName . " " . $lastName; // Prints Michael Boguslavskiy ?>
Now let’s say all we really want to do is just replace that dash within our
$fullName variable with a space. PHP has another function for that called
str_replace. We simply tell it what we want to look for, what we want to replace it with, and within what string. So in our case:
<?php $fullName = "Michael-Bogusla,vskiy"; $fullName = str_replace("-", " ", $fullName); echo $fullName; // Prints Michael Boguslavskiy ?>
str_replace function can also perform multiple replacements at the same time. Any of the three parameters may be specified as arrays. The first parameter may be an array of several different substrings to find within the string. Once found, the corresponding element of the array passed as the second parameter is used as the replacement string. If the second parameter was a single string, then that string will be used for all of the replacements. This can go on for however many strings are in the array passed as the third parameter, which may or may not be an array. For example, let’s say we had a string where we wanted to replace all weird characters with a space:
<?php $fullName = "Mich*ael-Bogus.lavskiy"; $symbols = Array("-", ".", "*"); $fullName = str_replace($symbols, " ", $fullName); echo $fullName; // Displays Mich ael Bogus lavskiy ?>
Let’s take a look at a more real world example. Assume that we are working on a commenting system for our website and we want to make sure we avoid specific curse words within our text and replace them with something nicer. As mentioned above we can pass two arrays to the
str_replace function making PHP replace all of the specified text within the first array with the corresponding text from the other array.
<?php $string = "This house looks like crap and the dog is a bitch."; $curses = Array("crap", "bitch"); $niceWords = Array("poopy", "female dog"); $string = str_replace($curses, $niceWords, $string); echo $string; // Will display: This house looks like poopy and the dog is a female dog. ?>