php - 用于创建 slug 的 mySQL 存储函数

标签 php mysql function

是否有 mysql 存储函数可以从 url(或任何值)创建 slug。

所以我的查询可以是:

SELECT *, SLUG(url) FROM clients

最佳答案

这是 Robert Ross 答案的改进版本。它的速度要快得多,因为它避免了遍历所有允许的字符,而只是通过比较 ASCII 代码进行检查。

DROP FUNCTION IF EXISTS `slugify`;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost`
FUNCTION `slugify`(dirty_string varchar(200))
RETURNS varchar(200) CHARSET latin1
DETERMINISTIC
BEGIN
    DECLARE x, y , z Int;
    Declare temp_string, new_string VarChar(200);
    Declare is_allowed Bool;
    Declare c, check_char VarChar(1);

    set temp_string = LOWER(dirty_string);

    Set temp_string = replace(temp_string, '&', ' and ');

    Select temp_string Regexp('[^a-z0-9\-]+') into x;
    If x = 1 then
        set z = 1;
        While z <= Char_length(temp_string) Do
            Set c = Substring(temp_string, z, 1);
            Set is_allowed = False;
            If !((ascii(c) = 45) or (ascii(c) >= 48 and ascii(c) <= 57) or (ascii(c) >= 97 and ascii(c) <= 122)) Then
                Set temp_string = Replace(temp_string, c, '-');
            End If;
            set z = z + 1;
        End While;
    End If;

    Select temp_string Regexp("^-|-$|'") into x;
    If x = 1 Then
        Set temp_string = Replace(temp_string, "'", '');
        Set z = Char_length(temp_string);
        Set y = Char_length(temp_string);
        Dash_check: While z > 1 Do
            If Strcmp(SubString(temp_string, -1, 1), '-') = 0 Then
                Set temp_string = Substring(temp_string,1, y-1);
                Set y = y - 1;
            Else
                Leave Dash_check;
            End If;
            Set z = z - 1;
        End While;
    End If;

    Repeat
        Select temp_string Regexp("--") into x;
        If x = 1 Then
            Set temp_string = Replace(temp_string, "--", "-");
        End If;
    Until x <> 1 End Repeat;

    If LOCATE('-', temp_string) = 1 Then
        Set temp_string = SUBSTRING(temp_string, 2);
    End If;

    Return temp_string;
END;;
DELIMITER ;

关于php - 用于创建 slug 的 mySQL 存储函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5409831/

相关文章:

php - 如何在独立代码中使用 Symfony Messenger 组件发送 AMQP 消息

mysql - 预加载带条件的嵌套资源

MySQL 从 7 月 1 日午夜开始消耗 80-100% 的 CPU,也就是 EBS 连接问题发生后的一天左右

function - Node-red - 需要一个数字值的多输入函数

php - 显示 php 函数中的错误

PHP 7 文档 block 和函数返回类型?

php - Laravel 5.2 单元测试集标题不起作用

php - 使用 PHP 缩小内联 JavaScript

phpmyadmin中mysql版本不同

javascript - 对象中的函数指针