问题
this is my approach, with no success anyways, but maybe it gives you an idea of what both my code and coding skills are like, as well as what I am trying to achieve.
$data1 = mysql_query("SELECT * from `todolist` WHERE date > '$today' ")
or die(mysql_error());
$data1b = str_replace("text-to-be-replaced", "replaced-text", $data1);
while($info1 = mysql_fetch_array( $data1b ))
{
Print "".$info1['thingtobedone'] . " with ".$info1['persontomeet'] . "<br />";
}
Also, my approach is incorrect since what I would like to do is set a bunch of search and replace cases. Something like a list of "search for X and replace for Y" instead of only one replacement. Originally i thought of doing something like "replace A for B and rename array as STEP2", then get array called STEP2 and "search for C and replace it for D, and rename array as STEP3" but...i think this might not be the best way to do so =/
Any recommendations, pointers, corrections will be appreciated! Thanks in advance!
回答1:
You can use the strtr() function in PHP to pass in a key => value pair of replacement rules:
$data = mysql_query('SELECT * FROM todolist WHERE date > CURDATE()') or die(mysql_error());
// Array of replacement rules. Keys of the array are strings to be replaced.
// Corresponding values of the keys are the replacement strings
$trans = array(
'stringtoreplace1' => 'replacedstring1',
'stringtoreplace2' => 'replacedstring2',
'stringtoreplace3' => 'replacedstring3'
);
while($info = mysql_fetch_array($data))
{
print strtr($info['thingtobedone'], $trans) . ' with ' . $info['persontomeet'] . '<br />';
}
Assuming thingtobedone
is the column you want to make the replacements on.
Then when you call strtr($info['thingtobedone'], $trans)
, the function will take the string and replace all occurances of every key value in the $trans
array with their corresponding values. It's a nice way to make many string-replacements all at once.
来源:https://stackoverflow.com/questions/11606396/php-replace-text-inside-an-array-resulting-from-query