Today I wanted to talk about the String Replace function in PHP. This function allows us to do multiple things, I like it specifically to be able to store information like a page layout in my database. The problem is that some things need to be dynamic. I use string replace to achieve this.
For example, if members logged into my website maybe I would want a part to say something like "Hello Blain". Overall it seems pretty easy but if I am storing the page content itself in the database to be recalled whenever a member logs in, I cannot make the "Blain" part dynamic. It will always say Blain, unless I use string replace.
When preparing to use string replace, I need to setup the page to properly have the right variable. I tend to use hashtags to identify pieces of information that will need to be replaced. So in this example, I will use #FIRSTNAME# wherever I want the members first name to appear. Then when I load the page, I run a simple function to replace #FIRSTNAME# with the members first name. This gives the member a unique experience!
Getting into the function itself, string replace will look like this in PHP:
str_replace ($search, $replace, $content);
$search is what I am searching for, in this case it would be #FIRSTNAME#
$replace is what I am replacing it with, which would be something like Blain, Jon, Mary, Elizabeth, etc.. depending on the user
$content is the content itself that I pulled from the database.
So in a simplified version this is what it may look like:
$content = $database_content;
$member_firstname = $name_from_database;
$newcontent = str_replace("#FIRSTNAME#",$member_firstname,$content);
So I pulled the page content from the database as $content. I then pulled the members first name from the database as $member_firstname. And lastly I ran the string replace function with the result being $newcontent. Then I echoed $newcontent to display the result on the page.