essaji Posted January 31, 2013 Share Posted January 31, 2013 I am just now starting to learn PHP. I know there are very useful functions available to replace a word in a string but I am doing at my own for learning purpose. The following is the code that I have written to search a word within a string. But the output is not what I am expecting. Please take look at this code and tell where I am doing it wrong. Code: <?php $string = 'That\'s a simple string. I want to replace a word in this string. I am very fond of eating apples and what about you? I think you are also fond of eating apples right?'; $find = 'apples'; $replace = 'banana'; $find_length = strlen($find); $offset = 0; while($string_position = strpos($string, $find, $offset)) { $new_string = substr_replace ($string, $replace, $string_position , $find_length); $offset = $string_position + $find_length; } echo $new_string; ?> Output: That's a simple string. I want to replace a word in this string. I am very fond of eating apples and what about you? I think you are also fond of eating banana right? See the output. The first word 'apples' is not replaced by the word 'banana' but the second word 'apples' in the string is replaced with the word 'banana' as expected. Thanks in anticipation. Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 31, 2013 Share Posted January 31, 2013 The problem is simple. Step through each line of code and figure out what would happen and/or echo the values of key variables before and after changes are made. Those are key debugging techniques and would allow you to find the problem yourself. But, I'll be nice and just tell you the problem. The loop is executing twice and it does replace the first occurrence of 'apple'. But, look how you get your $new_string $new_string = substr_replace ($string, $replace, $string_position , $find_length); It defines $new_string as the ORIGINAL string with the current replacement. So, on the first loop it defines $new_string as the original string with the first occurrence of 'apple' replaced. Then on the second iteration of the loop it REDEFINES $new_string as the ORIGINAL string with the second occurrence of 'apple' replaced. So, you lose the first replacement. $string = 'That\'s a simple string. I want to replace a word in this string. I am very fond of eating apples and what about you? I think you are also fond of eating apples right?'; $find = 'apples'; $replace = 'banana'; $find_length = strlen($find); $offset = 0; $new_string = $string; while($string_position = strpos($new_string, $find, $offset)) { $new_string = substr_replace ($new_string, $replace, $string_position , $find_length); $offset = $string_position + $find_length; } echo $new_string; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.