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.



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:


The 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:


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.


Published by Michael Boguslavskiy

Michael Boguslavskiy is a full-stack developer & online presence consultant based out of New York City. He's been offering freelance marketing & development services for over a decade. He currently manages Rapid Purple - and online webmaster resources center; and Media Explode - a full service marketing agency.

Leave a comment

Your email address will not be published. Required fields are marked *