php - 如何计算忽略空格的字符串中的前 30 个字母

标签 php

我想获取帖子描述,但只显示第一个,例如 30 个字母,但忽略任何制表符和空格。

$msg = 'I only need the first, let us just say, 30 characters; for the time being.';
$msg .= ' Now I need to remove the spaces out of the checking.';

$amount = 30;

// if tabs or spaces exist, alter the amount
if(preg_match("/\s/", $msg)) {
    $stripped_amount = strlen(str_replace(' ', '', $msg));
    $amount = $amount + (strlen($msg) - $stripped_amount);
}

echo substr($msg, 0, $amount);
echo '<br /> <br />';
echo substr(str_replace(' ', '', $msg), 0, 30);

第一个输出给我 '我只需要第一个,让我们说,30 个字符;' 第二个输出给我:Ionlyneedthefirst,letusjustsay 所以我知道这没有按预期工作。

在这种情况下我想要的输出是:

I only need the first, let us just say

提前致谢,我的数学很烂。

最佳答案

您可以使用正则表达式获取前 30 个字符的部分:

$msg_short = preg_replace('/^((\s*\S\s*){0,30}).*/s', '$1', $msg);

使用给定的 $msg 值,您将得到 $msg_short:

I only need the first, let us just say

正则表达式的解释

  • ^:匹配必须从字符串的开头开始
  • \s*\S\s* 一个非空白字符 (\S) 被零个或多个空白字符 (\s *)
  • (\s*\S\s*){0,30} 重复查找此序列最多 30 次(贪婪;在该限制内尽可能多地查找)
  • ((\s*\S\s*){0,30}) 括号使这一系列字符组编号为1,可以引用为$1
  • .* 任何其他字符。这将匹配所有剩余的字符,因为末尾有 s 修饰符:
  • s:让点也匹配换行符

在替换中,只保留属于第一组 ($1) 的字符。所有其余部分都将被忽略,并且不会包含在返回的字符串中。

关于php - 如何计算忽略空格的字符串中的前 30 个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40664335/

相关文章:

php - 如何使用 PHP 删除不包含指定字符串的行?

php - laravel 队列与 redis 进程一次,需要运行 php artisan cache :clear for next job process

PHP输入表单,带有精确的金额数字

php - 当我使用内连接关键字时得到错误的数据

php - 如何在插入查询中获得 auto_increment 值?

javascript - 我正在构建一个 Youtube 订阅下载门..并且我希望在单击订阅按钮后出现一个按钮

php - 如何多次加入同一个表以检索不同的结果

javascript - 创建下拉页面

php - 如何对齐 fpdf 中的文本

php - 在 PHP echo 中放置一个 onCLICK