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


How to count the first 30 letters in a string ignoring spaces

我想取一个帖子描述,但只显示第一个,例如,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个字符;'第二个输出给我:只需要第一个,让我们只是说所以我知道这不是如预期的那样工作。

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

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:

我只需要第一个,我们直接写

正则表达式

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

在替换中只维护属于组1 ($1)的字符。

自然而然地,我想到了两种方法。

第一个和你已经做过的很接近。取前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;
$offset = 0;
$final_string = '';
while ($amount > 0) {
  $tmp_string = substr($msg, $offset, $amount);
  $amount -= strlen(str_replace(' ', '', $tmp_string));
  $offset += strlen($tmp_string);
  $final_string .= $tmp_string;
}
print $final_string;

第二种技术是在空格处将字符串分解,然后将它们一个接一个地组合在一起,直到达到阈值(最终需要将单个单词分解为字符)。

试一下,看是否有效:

<?php
$string= 'I only need the first, let us just say, 30 characters; for the time being.';
echo "Everything: ".strlen($string);
echo '<br />';
echo "Only alphabetical: ".strlen(preg_replace('/[^a-zA-Z]/', '', $string));
?>

可以这样做。

$tmp=str_split($string);//split the string
$result="";
$i=0;$j=0;
while(isset($tmp[$i]) && $j<30){
  if(trim($tmp[$i])){//test for non space and count
   $j++;
  }
 $result .= $tmp[$i++];
}
print $result;

我不太懂正则表达式,所以…

<?php
$msg = 'I only need the first, let us just say, 30 characters; for the time being. Now I need to remove the spaces out of the checking.';
$non_space_hit = 0;
for($i = 0; $i < strlen($msg); ++$i)
{
    echo $msg[$i];
    $non_space_hit+= (int)($msg[$i] !== ' ' && $msg[$i] !== "'t");
    if($non_space_hit === 30)
    {
        break;
    }
}

你最终得到:

我只需要第一个,我们直接写