Page 1 of 1

str_replace

Posted: Fri Oct 28, 2005 3:07 pm
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

Posted: Fri Oct 28, 2005 6:54 pm
by feyd
are you sure $msg is set correctly when you start the str_replace batch calls?

Posted: Fri Oct 28, 2005 10:02 pm
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'

Posted: Fri Oct 28, 2005 10:12 pm
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.

Posted: Fri Oct 28, 2005 10:56 pm
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