0

我需要将文本分成此函数所做的两部分,但它会在单词中间中断,我需要它来计算单词的开头或结尾,给或取几个字符。

我不能基于字数,因为我需要字符范围不超过 130 个字符。

$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem     Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown     printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum"

$first125 = substr($str, 0, 125);
$theRest = substr($str, 125);

谢谢

4

3 回答 3

2

尝试:

<?php
$str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem     Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown     printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum";
$str = explode(' ', $str);
$substr = "";

foreach ($str as $cur) {
    if (strlen($substr) >= 125) {
        break;
    }
    $substr .= $cur . ' ';
}
echo $substr;
?>

密码板:http : //codepad.org/EhgbdDeJ

于 2012-09-21T14:02:41.253 回答
1

这是一个非常基本的解决方案,可以帮助您入门

$first125 = substr($str, 0, 125);
$theRest = substr($str, 125);

$remainder_pieces = explode(" ", $theRest, 2);

$first125 .= $remainder_pieces[0];
$theRest = $remainder_pieces[1];

echo $first125."</br>";
echo $theRest;

但是还有更多的事情需要考虑,例如在该解决方案中,如果第 125 个字符是一个单词结束后的空格,它将包含除此之外的另一个单词,因此您可能需要添加一些额外的检查方法来尝试使其尽可能准确。

于 2012-09-21T14:00:22.153 回答
0

不确定是否有一个本机 php 函数不在我的脑海中,但我认为这应该适合你。当然,您需要添加一些内容来检查是否至少有 125 个字符以及假设的第 125 个字符之后是否有空格。

    $k = 'a';
    $i = 0;
    while($k != ' '):
       $k = substr($str, (125+$i), 1);
       if($k == ' '):
         $first125 = substr($str, 0, (125+$i));
         $theRest = substr($str, (125+$i+1));
       else:
             $i++;
       endif;
    endwhile;
于 2012-09-21T14:00:01.960 回答