hello fellas.. i have this problem replacing a specific word with a variable...for example: -------------example.php contains this ------------- $string = "My name is [Name] what's yours?"; $NewString = str_replace('[Name]','$myname',$string); ---------------------------------------------------- -------------names.php contains the names----------- $myname = "James bond"; ------------------------------------------------------ so my final code will look like this: in names.php file.... ------------------------- include 'example.php'; $myname = "James bond"; echo $NewString; ------------------------- now it should output 'My name is James bond what's yours?' but when i tested it it shows the variable $myname instead... the problem is that i have to replace the word with variable before i put that variable inside the replace function.. any ideas?
Hi, Try removing the ' ' around the variable $myname. $NewString = str_replace('[Name]',$myname,$string); Regards, Steve
you didnt understand what im trying 2 do... okay lemme give another example: I have this emailing script. I wanna do a custom message which contains the [name] tag that will read the variables of emails instead... so simply i need to replace this [name] tag with the email variable.. coz from time to time i need 2 update this custom message from the database.. and i dont want to change it from my source code.. for instance: i have textbox to update this message. this textbox will output my message with the places of possible areas I can replace with varibles.. so if I insert [name] tag 3 times it should echo the name inside my variable 3 times...did u get the idea?
Hello, if you use stre_replace with '$variable_name' instead of $variable_name as the second parameter, it will take the sting '$variable_name' and not it's content. Another way of doing so is by using double quotes like this : echo "Hello $bob"; It saves one step. Have a great day!
Rather than replacing the String why don't you just put the variable in the output like: "My name is $name what's yours?"; and if you need to use str_replace Steve was correct.
The problem here is that by the time you set $myname after including example.php, the str_replace() function has already been executed (at that time $myname wasn't set, and thus blank). Try putting the $myname line ABOVE the include of example.php
why don't you use a small function such as function replace_name($myname){ return "My name is ".$myname." what's yours?"; } PHP: