【问题标题】:Strip character in a php 'for' loop/mysql query在 php 'for' 循环/mysql 查询中去除字符
【发布时间】:2012-05-31 05:26:48
【问题描述】:

我有一个成功显示帐号的循环。其中一些数字以“@”开头保存到数据库中。我想从显示的结果中去掉“@”符号。我已经看到了很多简单的回显解决方案,它们通过使用trimpreg_replace 等来实现这一点,但在for 循环中什么都没有。有什么想法吗?

我当前的代码(不包括尝试的解决方案):

<?php
$query = sprintf("SELECT banner_id FROM tablename") or die(mysql_error());
$result = mysql_query($query, $dblink) or die(mysql_error());
$i = 0;
if($result){
  while($row = mysql_fetch_array($result)){
    $banner_id[$i] = $row['banner_id'];
    $i++;
  }
}
?>
<html><body>
<ul>
<?php     
    for($x=0; $x < mysql_num_rows($result); $x++) {
        echo "<li>{$banner_id[$x]}</li>\n";
    }
?>
</ul>
</body></html>

电流输出:

  • 12345678
  • @98765432
  • @01230145

期望的输出:

  • 12345678
  • 98765432
  • 01230145

我觉得这应该很容易,但我找不到任何可行的方法。感谢您提供的任何帮助!

【问题讨论】:

  • 请停止使用古老的mysql_* 函数编写新代码。它们不再维护,社区已经开始 deprecation process 。相反,您应该了解prepared statements 并使用PDOMySQLi。如果您无法决定,this article 将帮助您选择。如果你想学习,here is a quite good PDO-related tutorial.
  • 循环结构中的变量并没有什么神奇之处。不确定您的问题是什么,因为您没有说您尝试过的方法不起作用。您只是表明无论您尝试什么都行不通。显示什么不起作用。

标签: php mysql for-loop character strip


【解决方案1】:

我不明白为什么你认为你不能在 for 循环中使用 trim()

<?php     
    for($x=0; $x < mysql_num_rows($result); $x++) {
        $out = ltrim($banner_id[$x], '@');
        echo "<li>$out</li>\n";
    }
?>

【讨论】:

  • 既然只需要从一开始就删除肯定使用ltrim会更有效吗?
  • 谢谢,洛伦佐。我尝试了类似的东西,但我只是偏离了标准。您的解决方案(以及——是的,尼克——使用ltrim)运行良好。你们摇滚。
【解决方案2】:
while($row = mysql_fetch_array($result)){
    $banner_id[$i] = trim( $row['banner_id'], '@' );
    $i++;
}

您发现可以在打印期间执行的任何操作也可以在打印之前进行。不过,我会避免在这样的简单替换中使用 preg_* 函数。


编辑:看到其他 cmets 后,我意识到 str_replacetrim 慢得多,trimltrim 稍微快。

我的测试代码:

<?php
$start = microtime(true);
for($i = 0; $i < 1000000; $i++)
{
    $test = '@123345567';
    $test = str_replace('@', '', $test);
}

$time = microtime(true) - $start;
print "str_replace(): $time";

$start = microtime(true);
for($i = 0; $i < 1000000; $i++)
{
    $test = '@123345567';
    $test = trim($test, '@');
}

$time = microtime(true) - $start;
print "<br/>trim(): $time";

$start = microtime(true);
for($i = 0; $i < 1000000; $i++)
{
    $test = '@123345567';
    $test = ltrim($test, '@');
}

$time = microtime(true) - $start;
print "<br />ltrim(): $time";

一些结果:

str_replace(): 0.64844393730164
trim(): 0.50381588935852
ltrim(): 0.51557087898254

str_replace(): 0.65361404418945
trim(): 0.49786400794983
ltrim(): 0.51703000068665

str_replace(): 0.64999985694885
trim(): 0.49114680290222
ltrim(): 0.5248019695282

【讨论】:

【解决方案3】:

你试过用echo "&lt;li&gt;".ltrim($banner_id[$x], '@')."&lt;/li&gt;\n";吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 2012-11-22
    • 1970-01-01
    相关资源
    最近更新 更多