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

Jaq*_*arh 6 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);
Run Code Online (Sandbox Code Playgroud)

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

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

I only need the first, let us just say
Run Code Online (Sandbox Code Playgroud)

提前谢谢,我的数学很糟糕.

tri*_*cot 5

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

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

使用给定的$msg值,您将进入$msg_short:

我只需要第一个,让我们说

正则表达式的说明

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

在替换中,仅维护属于组one($1)的字符.所有其余的都被忽略,并且不包含在返回的字符串中.

  • 你可以在[regex101.com](https://regex101.com/r/xzwNFi/1)上玩这个.另见[关于正则表达式的一些教程](http://www.regular-expressions.info/tutorial.html). (2认同)