PHP函数——自定义字符串长度函数

发布于 2024-10-05 02:18:28 字数 157 浏览 0 评论 0原文

在php中,有什么函数可以只显示长度大于50个字符的字符串,将其截断以不显示超过130个字符并将其限制为一个结果?

例如,假设我的结果集中有 30 行,但我只想显示具有这些参数的最新行。如果最新行有 25 个字符,则不应显示。它应该只显示字符串长度为 50 个或更多字符的最新字符串。

In php what is a function to only display strings that have a length greater than 50 characters, truncate it to not display more than 130 characters and limit it to one result?

so for example say i have 30 rows in a result set but I only want to show the newest row that have these parameters. If the newest row has 25 characters it should not display. It should only display the newest one that has a string length of 50 or more characters.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

∞琼窗梦回ˉ 2024-10-12 02:18:28

使用 SQL 查询。为了查找最新的,您需要在 auto_increment 主键(我称之为 id)或创建行时的日期/时间(例如时间 time_created)上获得 max 值。

因此,我假设表具有: id (int)、stringVal (string、char()、varchar() 等)

SELECT MAX(id),  SUBSTRING(stringVal, 1, 130)
FROM yourTable
WHERE LENGTH(stringVal) > 30

如果需要,请将 id 替换为时间字段。如果没有其中之一,您将很难找到最新的,但您始终可以任意选择一行。

--编辑-- 在 PHP 中使用 mysql 函数运行上述查询并获取所需输出的示例

$sql = "SELECT MAX(id),  SUBSTRING(stringVal, 1, 130) FROM yourTable WHERE LENGTH(stringVal) > 30";
$r = mysql_query($sql, $conn); //im hoping $conn or something like it is already set up
$row = mysql_fetch_assoc($r);
$desiredString = $row['stringVal'];

Use an SQL query. For finding the newest you want max on either an auto_increment primary key (ill call it id) or a date/time when the row was created (say, time time_created).

So I am assuming table with: id (int), stringVal (string, char(), varchar(), whatever)

SELECT MAX(id),  SUBSTRING(stringVal, 1, 130)
FROM yourTable
WHERE LENGTH(stringVal) > 30

Replace id with a time field if you have to. You're going to have a hard time finding the newest without one of them, but you can always arbitrarily pick one row.

--Edit-- a sample of using mysql functions in PHP to run above query and fetch desired output

$sql = "SELECT MAX(id),  SUBSTRING(stringVal, 1, 130) FROM yourTable WHERE LENGTH(stringVal) > 30";
$r = mysql_query($sql, $conn); //im hoping $conn or something like it is already set up
$row = mysql_fetch_assoc($r);
$desiredString = $row['stringVal'];
夜光 2024-10-12 02:18:28

像这样的事情应该做的只是确保您首先按最新项目排序获取数据。 Break 语句将确保在找到第一个与您的条件匹配的结果后终止循环...

foreach($array_returned_from_query as $row)
{
    if(strlen($row) > 50)
    {
        echo substr($row, 0, 130);
        break;
    }
}

Something like this should do just make sure that you grab your data sorting by the newest items first. The break statement will ensure that the loop is terminated after the first result matching your criteria is found...

foreach($array_returned_from_query as $row)
{
    if(strlen($row) > 50)
    {
        echo substr($row, 0, 130);
        break;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文