我正在为个人社交媒体链接添加个人表单(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/
3条答案
按热度按时间fwzugrvs1#
在这个TikTok page上,我发现用户名的要求是:
用户名只能包含字母、数字、下划线和句点。但是,不能在用户名末尾加上句点。
如果您声明用户名最多可以有24个字符(我假设最小长度为1个字符),您可以匹配0-23个允许的字符,包括一个点,并排除用户名末尾的点。
请注意,如果您只提供句柄,并且同一句柄对instagram有效,则必须确定优先级。
我不确定所有可用的TikTok URL,但如果你想使用锚点匹配整个URL,以及http(s)和www.部分是可选的:
说明
^
字符串开头(?:
非捕获组(?:https?://)?
匹配可选http://或https://(?:www\.)?
匹配可选www.tiktok\.com/
匹配tiktok.com/
)?
关闭非捕获组并使其可选@
按字面匹配([\w.]{0,23}\w)
(?:/\S*)?
可选匹配/
和可选非空格字符$
字符串结束Regex demo
如果在PHP中使用不同于
/
的分隔符,则不必转义正斜杠。h7wcgrx32#
您可以使用
parse_url
将字符串解析为URL(不用担心,只有用户名的字符串仍然会被解析并添加为路径,只要它们不包含任何URL特定的字符):j8yoct9x3#
您需要使用下面的函数来检查多个平台的相同函数