問題描述
我在函數中使用了模式 /[a-z0-9_]+/i
:
I have used the pattern /[a-z0-9_]+/i
within the function:
function validate_twitter($username) {
if (eregi('/[a-z0-9_]+/i', $username)) {
return true;
}
}
通過這個,我測試輸入是否是有效的 twitter 用戶名,但我遇到了困難,因為它沒有給我一個有效的結果.
With this, I test if the input is a valid twitter username, but i'm having difficulties as it is not giving me a valid result.
誰能幫我找到解決辦法.
Can someone help me find a solution.
推薦答案
驗證字符串是否為有效的 Twitter 句柄:
To validate if a string is a valid Twitter handle:
function validate_username($username)
{
return preg_match('/^[A-Za-z0-9_]{1,15}$/', $username);
}
如果您嘗試在字符串中匹配 @username
.
If you are trying to match @username
within a string.
例如:RT @username: lorem ipsum @cjoudrey etc...
使用以下內容:
$string = 'RT @username: lorem ipsum @cjoudrey etc...';
preg_match_all('/@([A-Za-z0-9_]{1,15})/', $string, $usernames);
print_r($usernames);
您可以將后者與 preg_replace_callback 結合使用以鏈接字符串中的用戶名.
You can use the latter with preg_replace_callback to linkify usernames in a string.
Twitter 還開源文本庫用于 Java 和Ruby 用于匹配用戶名、哈希標簽等.您可以查看代碼并找到它們使用的正則表達式模式.
Twitter also open sourced text libraries for Java and Ruby for matching usernames, hash tags, etc.. You could probably look into the code and find the regex patterns they use.
編輯 (2):這是 Twitter 文本庫的 PHP 端口:https://github.com/mzsanford/twitter-text-php#readme
Edit (2): Here is a PHP port of the Twitter Text Library: https://github.com/mzsanford/twitter-text-php#readme
這篇關于如何使用正則表達式驗證 Twitter 用戶名的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!