PHP +替换查询产生的数组内的文本 [英] php + replace text inside an array resulting from query

查看:67
本文介绍了PHP +替换查询产生的数组内的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的方法,无论如何都没有成功,但是也许它使您了解我的代码和编码技能,以及我要达到的目标.

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 />";
 }


此外,我的方法是不正确的,因为我想做的是设置一堆搜索和替换用例. 类似于搜索X并替换Y"的列表,而不是仅替换一个列表.最初,我想到做将A替换为B,将数组重命名为STEP2",然后获取名为STEP2的数组,搜索C并将其替换为D,然后将数组重命名为STEP3",但是...我认为可能不会是这样做的最好方法=/


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!

推荐答案

您可以使用 strtr() 函数传递键=>值对的替换规则:

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 />';
}

假设thingtobedone是您要进行替换的列.

Assuming thingtobedone is the column you want to make the replacements on.

然后,当您调用strtr($info['thingtobedone'], $trans)时,该函数将采用字符串并将$trans数组中每个键值的所有出现都替换为它们的对应值.这是一次同时进行许多字符串替换的好方法.

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.

这篇关于PHP +替换查询产生的数组内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆