Replacing a portion of a string with PHP
PHP/MySQL
Last Updated: 2007-03-03 13:30:35
Last Updated: 2007-03-03 13:30:35
STEP 1: The substr_replace() function
The substr_replace() function is allows you to replace a portion of a string. To do this you must provide the function with three arguments; the string you are changing, the text you want to add and the string index. This function also accepts a forth optional argument that sets the length of the string you are changing.
The substr_replace() function finds the portion of the string you want to change based on the starting index and the length you specified (if at all). It then replaces that portion of the string with the string you provided.
Here is the syntax:
<?
$original_string = "I can't believe it's not butter";
$new_string = substr_replace($original_string, "do", 2, 5);
print "New string equals: " . $new_string;
// prints "New string equals: I do believe it's not butter"
?>
What we did in the above example is replace the word "can't" with the word "do". We start replacing the original string after the second character and we replace the next 5 characters with the string "do".
The substr_replace() function finds the portion of the string you want to change based on the starting index and the length you specified (if at all). It then replaces that portion of the string with the string you provided.
Here is the syntax:
<?
$original_string = "I can't believe it's not butter";
$new_string = substr_replace($original_string, "do", 2, 5);
print "New string equals: " . $new_string;
// prints "New string equals: I do believe it's not butter"
?>
What we did in the above example is replace the word "can't" with the word "do". We start replacing the original string after the second character and we replace the next 5 characters with the string "do".
This is the JoeLucky39 tutorial section. Feel free to use whatever information you find here on your own site(s). Know that not all tutorials are ideal for all sites, so feel free to modify the information contained in this tutorail section as best suits your web site.
At JoeLucky39 you can find tutorials on Comic Art, PHP/MySQL, and more are added all the time. So, visit often and feel free to contact Joe if you think that his tutorials need to be changed or updated.
Joe believes in the open source movement and is happy to share his knowledge with anyone who asks. All Joe asks is, if you use Joe's open source tutorials, you share your knowledge as well.
Thank you and I hope you find what you are looking for. If not feel free to contact me and ask.
