开发者

Unique slugs that, if fits with slug-1, slug-2... slug-n

I am using only slug to identify a page on the website, like: example.tld/view/this-fancy-slug . This is generated from the title automatically with this function:

public static function Normalize($str)
{
    $charset = "UTF-8";
    $separator = "-";

    $str = strtolower(htmlentities($str, ENT_COMPAT, $charset));
    $str = preg_replace('/&(.)(acute|cedil|circ|lig|grave|ring|tilde|uml);/', "$1", $str);
    $str = preg_replace('/([^a-z0-9]+)/', $separator, html_entity_decode($str, ENT_COMPAT, $charset));
    $str = trim($str, $separator);

    return $str;
}

This returns a perfect slug... but I need unique slugs. So I've to combine with mysql to check if exists a slug that fits with the created. No problem with that.

The problem is that I want to add a -1 at the final if there is ONE slug. But can be buggy if are added 3 equa开发者_运维百科l slugs so... how can I manage this to go from slug, slug-1, slug-2, slug-3... slug-100, slug-n?

Thank you in advance!


Don't just check if that identical slug is present. Use a regular expression to count all the slugs that follow the pattern /(<base-regex-for-slug>)(-\d+)?/. Because you only allow alphanumerics your base regex above will be the slug itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜