【问题标题】:Why is the substr(...) not doing what I want it to do?为什么 substr(...) 没有做我想做的事?
【发布时间】:2015-11-13 06:43:06
【问题描述】:

我有一段代码用于生成我网站上工作列表的预览。这应该是不言自明的,但我试图在我的数据库中获取 VARCHAR (5000) 类型列的前 100 个字符。

            $Jobs = $wpdb->get_results('SELECT * FROM jobs');
            foreach ($Jobs as $thisJob)
            {
                // use first 100 characters of job description before a "Read more" link to the full description
                echo  ' <div class="job-row">'
                      .   '<h3 class="job-title">' . $thisJob->title . '</h3>'
                      .   '<div class="job-descr-brief">'
                      .        substr($thisJob->descr, 100) . ' <a href="' . get_site_url . '/about/careers/?jobid=' . $thisJob->id . '">Read more.</a>'
                      .   '</div>'
                      .'</div>';
            }

然而,由于某种原因,substr($thisJob-&gt;descr, 100) 正在返回完整的 $thisJob-&gt;descr 字符串,而不仅仅是前 100 个字符。知道我在这里做错了什么吗?

相关文档:http://www.w3schools.com/php/func_string_substr.asp

【问题讨论】:

  • string substr ( string $string , int $start [, int $length ] ) php.net/substr
  • 您想使用substr($thisJob-&gt;descr, 0, 100)。始终使用 php.net 手册,而不是 w3schools,只是为了将来。
  • 看起来很奇怪,示例代码中的函数调用显然仍在输出完整的字符串,而没有删除前 100 个字符。
  • 啊,等一下:$thisJob->descr 的长度是否少于 100 个字符并且您正在运行 5.2.2 之前的 PHP 版本? Charlotte Dunois 链接中的版本 cmets 说:“5.2.2 - 5.2.6 如果 start 参数指示负截断或超出的位置,则返回 false。其他版本从 start 获取字符串。" 所以,我认为您可能正在运行旧版本的 PHP,并且输入的参数比字段内容的长度长,所以它根本不会截断它。
  • @dspitzle 你确定吗?我刚刚运行了3v4l.org/9bukd,它针对 150 个 php 版本运行脚本,并且都产生了相同的输出,false

标签: php mysql wordpress wordpress-theming


【解决方案1】:

我认为您误读了文档。

您需要像这样使用它来获取前 100 个字符:

substr($thisJob-&gt;descr, 0, 100);

第二个参数是您希望它开始的位置(在本例中为 0,即开始)。

【讨论】:

    猜你喜欢
    • 2014-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-26
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    相关资源
    最近更新 更多