Php.. str replace?

Soldato
Joined
24 Nov 2002
Posts
16,378
Location
38.744281°N 104.846806°W
I'm posting a form to a processing page that, rather simplistically has: $export=$_POST[Text1];

However, the contents of Text will be something along the lines of $1 blah $2 etc... And at the moment it will just echo "$1 blah $2" rather than the contents of $1 and $2!!!!

Now I have been using (on a static, i.e. non-form posted page):

$1=mysql_result($result,$i,"a");
$2=mysql_result($result,$i,"b");

To convert the variables, however, if it sposted this processing is lost.

I'm guessing I need to do some kind of modifying to $export to replace, say "$1 blah $2" with "mysql_result($result,$i,"a"); blah mysql_result($result,$i,"b");"

Unless there is an easier way...?

Been using:

Code:
<?
$i=0;
while ($i < $num){
$export=$_POST[Text1];
$1=mysql_result($result,$i,"a");
$2=mysql_result($result,$i,"b");
$3=mysql_result($result,$i,"c");
$splitdata = explode(',', $3);
$totaldata = count($splitdata);

echo $export;

$i++;
}
?>
 
Last edited:
So if you have a string with "$foo $bar" in it, and $foo is 'hello' and $bar is 'world', you want the string to become "hello world"? Easy peasy:

Code:
<?php

$string = '$foo $bar';
$foo = 'hello';
$bar = 'world';

preg_match_all('#\$(\S+)#i', $string, $matches);
foreach ( (array) $matches[1] as $match ) {
	$string = str_replace("\$$match", $$match, $string);
}

echo $string; // "hello world"

?>
 
Back
Top Bottom