我正在尝试清理值,因为某些字符串的长度超过70个字符,所以我需要将其切掉。
这个想法是,如果长度大于70,则在最后一个逗号后将其切掉(将其删除),但是一些更长的字符串没有逗号,因此需要在中间的最后一个空格处切掉这些最大长度为70个字符,这样我们就不会出现部分单词。
我现在拥有的代码(无法正常工作)。
$str = substr($longstr, 0 , 70 , '');
$shortstr = substr($str, 0, strrpos($str.",", ","));
输出1(带逗号)
$longstr = 'Some strings are way to long and need to be cut of, yes realy because we need the space.';
$shortstr = 'Some strings are way to long and need to be cut of';
输出2(白色)
$longstr = 'Some strings are way to long and need to be cut of yes realy because we need the space.';
$shortstr = 'Some strings are way to long and need to be cut of';
答案 0 :(得分:1)
----编辑----
$maxlen = 70;
for ($i = strlen($str); !in_array($str[$i], array(" ", ",")) || $i >= $maxlen ; $i--)
{
$str = substr($str,0,$i);
}
看到它正常工作:https://tehplayground.com/3F4zhA4tjCQTiBfc
----老答案----
不漂亮,但可以正常工作
<?php
$chrs = array(","," ");
$maxLen = 25;
$str = "This is a , long ass string, with commas, ";
if (strlen($str) > $maxLen)
{
$cut = strrpos(substr($str,0,$maxLen),",");
$cut2 = strrpos(substr($str,0,$maxLen)," ");
if ($cut < $cut2)
{
$cut = $cut2;
}
echo substr($str,0,$cut);
}
strrpos查找字符串中字符的最后一个实例,对逗号进行运算,然后对空格进行运算,取较大的数字作为切入点
https://tehplayground.com/tKD4vdk6pfupVQan
如果您想查看它是否有效:/
答案 1 :(得分:1)
首先,削减源字符串的限制(没错,只有第四个参数是多余的:substr
函数只有三个参数):
$tempstr = substr($longstr, 0, 70);
接下来,找到空格或逗号的位置-取决于它们中的哪个更靠近有限字符串的末尾-并获取字符串直到该位置:
$shortstr = substr($tempstr, 0, max(strrpos($tempstr, ' '), strrpos($tempstr, ',')));
答案 2 :(得分:0)
使用您的示例和regexr尝试一些操作,您可以轻松地执行类似于以下操作的操作;
<?php
$longstr = 'Some strings are way to long and need to be cut of yes really because we need the space.';
$shortstr = trim(preg_replace('/(.){70}/', "$0", $longstr));
print $shortstr; // Will give; "Some strings are way to long and need to be cut of yes really because
Trim将删除结尾的空格,而preg_replace仅将前70个字符(包括空格,直到删除)添加到shortstr变量中
我知道由于开销原因,这不是用于较大数据集的最合适的选择,但这是我过去用来实现相同结果的东西,但是请注意以下内容将是有益的; < br /> 要使用此功能,由于rexex的性质及其所带来的开销,可能会降低所有页面的加载时间
答案 3 :(得分:0)
建议将字符串转换为数组,然后循环检查逗号是否在逗号处被切掉,否则在70后的第一个空格处被切掉
$arr1 = str_split($str);
if(in_array(',', $arr1){
if(count($arr1 > 70) {
//cut off at comma
}
} else {
if(count($arr1 > 70) {
//cut off at whitespace
}
}