0

在我的slug专栏中,我设置了限制,varchar = 100并且值将像这样存储

how-do-i-truncate-a-string-with-dynamic-length-url-slug

我希望 slug 是一个unique键,所以我slug用最后一个自动增量 id 更新值,新的 slug 值是:

how-do-i-truncate-a-string-with-dynamic-length-url-slug-10

所以这里最终last auto increment将是一个很大的数字..

preg_replace('/\s+?(\S+)?$/', '', substr($slugwithautoincrement, 0, 101));

有了这个preg_replace,它会删除我的auto increment number

问题 :

如何在不删除最后一个自动增量编号的情况下将值修复截断为 100 个字符?

所以结果应该是:

how-do-i-truncate-a-string-with-[....remove from here...]10
4

3 回答 3

1

Truncate first and then append the auto increment value.

Or do something like this:

$maxlength = 30;
$number = 1234567;
$string = "how-do-i-truncate-a-string-with-dynamic-length-url-slug";
$slug = substr($string, 0, $maxlength - strlen($number) - 1)."-".$number;
于 2012-04-04T09:56:05.700 回答
1

这是一种方法:

$slug = "how-do-i-truncate-a-string-with-dynamic-length-url-slug-10"
$maxlen = 100;
if (strlen($slug) > $maxlen) {
    $idlen = strlen($slug) - strrpos($slug, '-'); // how long is the "-10" part?
    $id = substr($slug, -$idlen);
    $slug = substr($slug, 0, $maxlen - $idlen).$id;
}
echo $slug;

$maxlen如果碰巧具有特定值,则此代码可能会在 id 之前以两个连字符结尾。不过,这应该不是问题。

于 2012-04-04T09:59:17.530 回答
1

如果在附加自动增量值之前无法截断:

$slug = explode('-', $slug);

$value = array_pop($slug);

$slug = substr(implode('-', $slug), 0, 99 - strlen($value)) . '-' . $value;
于 2012-04-04T09:59:52.240 回答