str_replace

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
elecktricity
Forum Contributor
Posts: 128
Joined: Sun Sep 25, 2005 8:57 pm
Location: Trapped in my own little world.
Contact:

str_replace

Post by elecktricity »

hey just a question but im trying to make it to were im using this and I want it to display a number + another number like this

page1.php

Code: Select all

<input type="text" name="msg">
<input type="text" name="value2">
//plus all the submit junk
page2.php

Code: Select all

<?PHP
$msg = str_replace("1", "1+$in", $msg);
$msg = str_replace("2", "2+$in", $msg);
$msg = str_replace("3", "3+$in", $msg);
$msg = str_replace("4", "4+$in", $msg);
$msg = str_replace("5", "5+$in", $msg);
$msg = str_replace("6", "6+$in", $msg);
$msg = str_replace("7", "7+$in", $msg);
$msg = str_replace("8", "8+$in", $msg);
$msg = str_replace("9", "9+$in", $msg);
$msg = str_replace("0", "0+$in", $msg);
echo $msg;
?>
assuming they only enter numbers why wont this work? lol

like if msg=123 it would output 1+2+22+23+2

edit: btw if you didnt get this $in = 2
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

are you sure $msg is set correctly when you start the str_replace batch calls?
User avatar
elecktricity
Forum Contributor
Posts: 128
Joined: Sun Sep 25, 2005 8:57 pm
Location: Trapped in my own little world.
Contact:

Post by elecktricity »

yea it worked and all, it did display the numbers but it display exeactly what 'a' equaled like if I put 'a' it echoed '1+$in' or something, but I ended up doing this and it did work...

Code: Select all

<?PHP
$1 = $1 + $in;
$2 = $2 + $in;
//continue
$msg = str_replace("1", "$1", $msg); 
$msg = str_replace("2", "$2", $msg); 
//continue
echo $msg;
?>
so if msg = '1 2' and in = '1' it would echo '2 3'
mickd
Forum Contributor
Posts: 397
Joined: Tue Jun 21, 2005 9:05 am
Location: Australia

Post by mickd »

the above didnt work because you told it to be replaced by a string
"1+$in"
the double quotes (") will tell php to scan through the stuff in the quotes and replace any variables with their values. so once it replaces the varaible (which should be 2) it would have the string "1+2".

EDIT: btw for that above you should look into the += sign to use.
$1 += $in which is the same as $1 = $1 + $in.
User avatar
elecktricity
Forum Contributor
Posts: 128
Joined: Sun Sep 25, 2005 8:57 pm
Location: Trapped in my own little world.
Contact:

Post by elecktricity »

I guess that would make sence lol, I will try that out using the () in it, yea i've heard of using the += but i've always did it that way (even though I dont use much math) and so i just keep doing it lol... like a habit
Post Reply