php preg_match验证Tiktok用户名

pu3pd22g  于 2023-05-16  发布在  PHP
关注(0)|答案(3)|浏览(320)

我正在为个人社交媒体链接添加个人表单(Instagram,Twitter和Tiktok)
我正在努力寻找正确的模式来验证Tiktok用户名。下面是我在Instagram上的pregmatch代码。谁能告诉我TIKTOK的模式是什么?表单必须接受整个url和/或仅接受句柄。即,如果某人仅提供了句柄@xyz或整个url www.tiktok.cpm/@xyz-则表单必须验证两者。
对于Instagram,我编写了以下正则表达式代码

public function validate($value) {
    $value = $this->clean($value);

    // Validate as Instagram username (1-30 word characters, starts with @,
    return preg_match('/^@\w(?:(?:\w|(?:\.(?!\.))){0,28}(?:\w))?$/', $value);
}

FYI函数clean如下所示

public function clean($value) {
        // Tolerate a link
        $url_matches = [];
        if (preg_match('/^https?:\/\/(?:www\.)?instagram\.com\/([\w.]+)\/?$/', $value, $url_matches)) {
            $value = '@' . $url_matches[1];
        }

        // Prepend with @ if not already present
        if (!preg_match('/^@/', $value)) {
            $value = '@' . $value;
        }

        return $value;
    }

编辑
TikTok用户名有24个字符的限制。句柄前面将自动带有一个“@”符号。用户名只能包含字母、数字、句点和下划线。
Tiktok帐户示例-https://www.tiktok.com/@imperialcollegeunion/
示例Instagram帐户-https://www.instagram.com/icunion/

fwzugrvs

fwzugrvs1#

在这个TikTok page上,我发现用户名的要求是:
用户名只能包含字母、数字、下划线和句点。但是,不能在用户名末尾加上句点。
如果您声明用户名最多可以有24个字符(我假设最小长度为1个字符),您可以匹配0-23个允许的字符,包括一个点,并排除用户名末尾的点。
请注意,如果您只提供句柄,并且同一句柄对instagram有效,则必须确定优先级。
我不确定所有可用的TikTok URL,但如果你想使用锚点匹配整个URL,以及http(s)和www.部分是可选的:

^(?:(?:https?://)?(?:www\.)?tiktok\.com/)?@([\w.]{0,23}\w)(?:/\S*)?$

说明

  • ^字符串开头
  • (?:非捕获组
  • (?:https?://)?匹配可选http://或https://
  • (?:www\.)?匹配可选www.
  • tiktok\.com/匹配tiktok.com/
  • )?关闭非捕获组并使其可选
  • @按字面匹配
  • ([\w.]{0,23}\w)
  • (?:/\S*)?可选匹配/和可选非空格字符
  • $字符串结束

Regex demo
如果在PHP中使用不同于/的分隔符,则不必转义正斜杠。

$pattern = "~^(?:(?:https?://)?(?:www\.)?tiktok\.com/)?@([\w.]{0,23}\w)(?:/\S*)?$~";
h7wcgrx3

h7wcgrx32#

您可以使用parse_url将字符串解析为URL(不用担心,只有用户名的字符串仍然会被解析并添加为路径,只要它们不包含任何URL特定的字符):

function parseUsername(string $value): string {

    $parsed = parse_url($value);
    // Break paths by / character, drop empty values
    $parsed['paths'] = array_values(array_filter(explode('/', $parsed['path'])));

    $username = '';

    // Default for all other usernames not included
    $regexp = '/^[a-zA-Z0-9\._]{2,50}$/';
    $username = ltrim($parsed['paths'][0] ?? '', '@');

    switch(true) {
        case preg_match(
                '/^(?:(?:www\.)?tiktok.com)$/i',
                $parsed['host'] ?? ''
            ): // tiktok
            // Letters, numbers, periods, underscores. No period at end.
            // Max 24 characters
            $regexp = '/^[a-zA-Z0-9\._]{2,24}(?<!\.)$/';
            // Username is in first path position, no need to change for tiktok
            break;
        case preg_match(
                '/^(?:(?:www\.)?instagram.com)$/i',
                $parsed['host'] ?? ''
            ): // instagram
            // Letters, numbers, periods, underscores.
            // Max 30 characters
            $regexp = '/^[a-zA-Z0-9\._]{2,30}$/';
            // Username is in first path position, no need to change for insta
            break;
    }

    if(preg_match($regexp, $username) == false) {
        // Invalid username found, throw an exception?
        throw new Exception('Invalid username provided.');
    }

    // Ensure username starts with @
    return '@' . $username;
}

var_dump(parseUsername('@coolname1')); // @coolname1
var_dump(parseUsername('coolname2')); // @coolname2
var_dump(parseUsername('https://www.instagram.com/mesh1.2')); // @mesh1.2
var_dump(parseUsername('https://www.tiktok.com/@not_a_valid_name.')); // Throws exception
j8yoct9x

j8yoct9x3#

您需要使用下面的函数来检查多个平台的相同函数

function clean($username, $platform) {
    $regex = '';
    switch ($platform) {
        case 'instagram':
            $regex = '/^[a-zA-Z0-9._]{2,30}$/';
            break;
        case 'tiktok':
            $regex = '/^[a-zA-Z0-9._]{2,}$/';
            break;
        default:
            return 'Invalid platform. Please choose either "instagram" or "tiktok".';
    }

    if (preg_match($regex, $username)) {
        return "Valid $platform username!";
    } else {
        return "Invalid $platform username!";
    }
}

相关问题