【问题标题】:php + replace text inside an array resulting from queryphp + 替换查询产生的数组中的文本
【发布时间】:2012-07-21 07:50:27
【问题描述】:

这是我的方法,无论如何都没有成功,但也许它让您了解我的代码和编码技能是什么样的,以及我想要实现的目标。


 $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”但是......我认为这可能不会成为这样做的最佳方式 =/

任何建议、指点、更正将不胜感激!提前致谢!

【问题讨论】:

  • 您希望对SELECT 语句中的哪一列执行替换?
  • “mysql_query”的返回值是资源,不是你要查找替换的数据

标签: php mysql loops while-loop


【解决方案1】:

可以使用PHP中的strtr()函数传入一个key => value对的替换规则:

$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 是您要在其上进行替换的列。

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

【讨论】:

  • 这太棒了!正是我需要的。此外,提供的解释也非常感谢。生病试一试,让你知道它是怎么回事!再次感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多