Use str_replace to Easier Delete Characters in a String with PHP
After I used the removeChars CF function yesterday, I was thinking that there should be a better way to delete the characters using words instead of numbers. I found an article that talks about using substr PHP function to delete the characters in a string with a negative number. For example, here is the code from the article:
$newstring = substr($string, 0, -4);
The output result removed last 4 characters in the string variable. However, this method is not what I need. I need a method to remove index file from the URL to form a complete URL. For instance, I would like to change example.com/account/index.php to example.com/account/.
After the extensive research on this topic, I came across with str_replace function on PHP.net. I thought I could use this function to easily delete the characters from a string without counting the number of characters to delete. I wrote the following code to delete the index.php in the SCRIPT_NAME string:
if (strstr($_SERVER['SCRIPT_NAME'], 'index.php')) {
$_SERVER['SCRIPT_NAME'] = str_replace("index.php", "", $_SERVER['SCRIPT_NAME']);
}
I used str_replace to replace “index.php” with an empty value in order to erase the selected characters. After the declaration of the new SCRIPT_NAME server string, I applied this variable to the home page link:
<a href="http://<?php echo $_SERVER['SERVER_NAME'].$_SERVER['SCRIPT_NAME']; ?>" title="Home Page">Home</a>
This method can be used to hide the file extension from users if you don’t want them to find out which server-side technology you are using
There are no posts related to Use str_replace to Easier Delete Characters in a String with PHP.