在距字符串开头不超过 N 个字符的空格之前截断句子

发布于 2024-10-05 11:52:11 字数 294 浏览 1 评论 0原文

我已经编写了用于获取给定动态句子的某些部分的 PHP 代码,例如 这是一个测试句子

substr($sentence,0,12);

我得到输出:

this is a te

但我需要它作为一个完整的单词停止而不是拆分一个单词:

this is a

我该如何做到这一点,记住 $sentence 不是固定字符串(它可以是任何东西)?

I have written the PHP code for getting some part of a given dynamic sentence, e.g. this is a test sentence:

substr($sentence,0,12);

I get the output:

this is a te

But I need it stop as a full word instead of splitting a word:

this is a

How can I do that, remembering that $sentence isn't a fixed string (it could be anything)?

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

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

发布评论

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

评论(8

绝對不後悔。 2024-10-12 11:53:32

这只是伪代码而不是 php,

char[] sentence="your_sentence";
string new_constructed_sentence="";
string word="";
for(i=0;i<your_limit;i++){
character=sentence[i];
if(character==' ') {new_constructed_sentence+=word;word="";continue}
word+=character;
}

new_constructed_sentence 就是你想要的!

this is just psudo code not php,

char[] sentence="your_sentence";
string new_constructed_sentence="";
string word="";
for(i=0;i<your_limit;i++){
character=sentence[i];
if(character==' ') {new_constructed_sentence+=word;word="";continue}
word+=character;
}

new_constructed_sentence is what you want!!!

深白境迁sunset 2024-10-12 11:53:26

创建一个可以随时重复使用的函数。如果给定字符串的长度大于您要修剪的字符数,这将查找最后一个空格。

function niceTrim($str, $trimLen) {
    $strLen = strlen($str);
    if ($strLen > $trimLen) {
        $trimStr = substr($str, 0, $trimLen);
        return substr($trimStr, 0, strrpos($trimStr, ' '));
    }
    return $str;
}

$sentence = "this is a test sentence";
echo niceTrim($sentence, 12);

这将

this is a

根据需要打印。

希望这是您正在寻找的解决方案!

Create a function that you can re-use at any time. This will look for the last space if the given string's length is greater than the amount of characters you want to trim.

function niceTrim($str, $trimLen) {
    $strLen = strlen($str);
    if ($strLen > $trimLen) {
        $trimStr = substr($str, 0, $trimLen);
        return substr($trimStr, 0, strrpos($trimStr, ' '));
    }
    return $str;
}

$sentence = "this is a test sentence";
echo niceTrim($sentence, 12);

This will print

this is a

as required.

Hope this is the solution you are looking for!

一身骄傲 2024-10-12 11:53:20

例如,如果您想匹配从字符串开头算起最多 12 个字符而不匹配尾随空格,则可以使用 \S 确保要匹配的最后一个字符是非空格字符,

然后您可以使用负前瞻断言之后的内容是右侧的空白边界。

^.{0,11}\S(?!\S)

部分模式:

  • ^ 字符串开头
  • .{0,11} 匹配 0 - 11 个字符
  • \S 匹配非空白字符
  • (?!\S) 负向前瞻,直接在右侧断言不是非空白字符

例如

$re = '/^.{0,11}\S(?!\S)/m';

$str = 'this is a test sentence
      this is a  test sentence  
a
           b
            c';

preg_match_all($re, $str, $matches);
var_export($matches[0]);

输出

array (
  0 => 'this is a',
  1 => '      this',
  2 => 'a',
  3 => '           b',
)

请参阅 PHP 演示正则表达式演示


如果您不需要前导空格在匹配 1 - 12 个字符之后,您可以使用所有格量词 + 将可选的前导水平空白字符与 \h*+ 进行匹配,以防止在没有匹配时出现不必要的回溯,并且然后使用 \K 忘记到目前为止匹配的内容。

$re = '/^\h*+\K.{0,11}\S(?!\S)/m';

$str = 'this is a test sentence
      this is a  test sentence  
a
           b
            c';

preg_match_all($re, $str, $matches);
var_export($matches[0]);

输出

array (
  0 => 'this is a',
  1 => 'this is a',
  2 => 'a',
  3 => 'b',
  4 => 'c',
)

请参阅 PHP 演示正则表达式演示

If you want to match for example at most 12 characters from the start of the string without matching trailing spaces, you can make sure that the last character to match is a non whitspace chararacter using \S

Then you can assert that what comes after that is a whitespace boundary at the right using a negative lookahead.

^.{0,11}\S(?!\S)

The pattern in parts:

  • ^ Start of string
  • .{0,11} Match 0 - 11 chars
  • \S Match a non whitespace char
  • (?!\S) Negative lookahead, assert not a non whitespace char directly to the right

For example

$re = '/^.{0,11}\S(?!\S)/m';

$str = 'this is a test sentence
      this is a  test sentence  
a
           b
            c';

preg_match_all($re, $str, $matches);
var_export($matches[0]);

Output

array (
  0 => 'this is a',
  1 => '      this',
  2 => 'a',
  3 => '           b',
)

See a PHP demo and a regex demo


If you don't want the leading spaces and after that match 1 - 12 characters, you could match optional leading horizontal whitespace characters with \h*+ using possessive quantifier + to prevent unnecessary backtracking when there is no match and then use \K to forget what is matched so far.

$re = '/^\h*+\K.{0,11}\S(?!\S)/m';

$str = 'this is a test sentence
      this is a  test sentence  
a
           b
            c';

preg_match_all($re, $str, $matches);
var_export($matches[0]);

Output

array (
  0 => 'this is a',
  1 => 'this is a',
  2 => 'a',
  3 => 'b',
  4 => 'c',
)

See a PHP demo and a regex demo.

无人问我粥可暖 2024-10-12 11:53:13

您的“句子”不包含任何标点符号,因此我假设所需的截断应出现在空格之前。

使用简单的正则表达式模式贪婪地匹配从字符串开头算起的 0 到 N 个字节,然后匹配一个空格,然后用 \K 忘记匹配的字符,然后匹配句子的其余部分。用空字符串替换该匹配项。

代码:(演示)

$text = 'this is a test sentence';

$max = 12;
var_export(
    preg_replace(
        "/.{0,$max}\K .*/",
        '',
        $text
    )
);
// 'this is a'

Your "sentence" doesn't contain any punctuation, so I'll assume that the desired truncation should occur before a space.

Use a simple regex pattern to greedily match between 0 and N bytes from the start of the string, then match a space, then forget the matched characters with \K, then match the rest of the sentence. Replace that match with an empty string.

Code: (Demo)

$text = 'this is a test sentence';

$max = 12;
var_export(
    preg_replace(
        "/.{0,$max}\K .*/",
        '',
        $text
    )
);
// 'this is a'
灼痛 2024-10-12 11:53:07

尝试使用 explode() 函数。

在你的情况下:

$expl = explode(" ",$sentence);

你将把你的句子放在一个数组中。第一个单词是 $expl[0],第二个单词是 $expl[1],依此类推。要将其打印在屏幕上,请使用:

$n = 10 //words to print
for ($i=0;$i<=$n;$i++) {
  print $expl[$i]." ";
}

Try using explode() function.

In your case:

$expl = explode(" ",$sentence);

You'll get your sentence in an array. First word will be $expl[0], second - $expl[1] and so on. To print it out on the screen use:

$n = 10 //words to print
for ($i=0;$i<=$n;$i++) {
  print $expl[$i]." ";
}
墨离汐 2024-10-12 11:52:59

第一的。在太空中使用爆炸。然后,计算每个部分+总的组装字符串,如果没有超出限制,则将其用空格连接到字符串上。

first. use explode on space. Then, count each part + the total assembled string and if it doesn't go over the limit you concat it onto the string with a space.

梦回旧景 2024-10-12 11:52:53

如果您使用 PHP4,则只需使用 split

$resultArray = split($sentence, " ");

数组的每个元素都是一个单词。不过要小心标点符号。

PHP5 中推荐使用 explode 方法:

$resultArray = explode(" ", $sentence);

If you're using PHP4, you can simply use split:

$resultArray = split($sentence, " ");

Every element of the array will be one word. Be careful with punctuation though.

explode would be the recommended method in PHP5:

$resultArray = explode(" ", $sentence);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文