我需要将文本拆分为这个函数所做的两个部分,但它在一个单词的中间切断,我需要它来计算一个单词的开头或结尾给出或取几个字符。
我不能以字数为基础,因为我需要字符范围不超过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);
由于
答案 0 :(得分: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;
?>
CodePad :http://codepad.org/EhgbdDeJ
答案 1 :(得分: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个字符是单词结束后的空格,它将包含除此之外的另一个单词,因此您可能需要添加一些额外的检查方法来尝试并尽可能准确。
答案 2 :(得分: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;