我想获取帖子描述,但只显示第一个,例如 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/