简体   繁体   English

如何截断动态长度为 url slug 的字符串?

[英]How do I truncate a string with dynamic length url slug?

On my slug column I set the limit is varchar = 100 and the values will store like this在我的slug列上,我将限制设置为varchar = 100并且值将像这样存储

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

I want the slug will be a unique key so I update the slug value with last auto increment id and new slug value is:我希望 slug 是一个unique键,所以我用最后一个自动递增 id 更新slug值,新的 slug 值是:

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

So here the last auto increment will be a big number at the end..所以这里last auto increment将在最后是一个大数字..

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

With this preg_replace it will remove my auto increment number使用此preg_replace它将删除我的auto increment number

Question:题:

How do I truncate the value fix to 100 characters without remove the last auto increment number?如何在不删除最后一个自动递增数字的情况下将值 fix 截断为 100 个字符?

So result should be:所以结果应该是:

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

Truncate first and then append the auto increment value.先截断再截断 append 自动增量值。

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;

Here's one way to do it:这是一种方法:

$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;

This code can possibly end up with two hyphens before the id if $maxlen happens to have specific values.如果$maxlen恰好具有特定值,则此代码可能会在 id 之前以两个连字符结尾。 That should not be a problem though.不过这应该不是问题。

If you can't truncate before appending the auto increment value:如果在附加自动增量值之前无法截断:

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

$value = array_pop($slug);

$slug = substr(implode('-', $slug), 0, 99 - strlen($value)) . '-' . $value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM