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;
}
}
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 unfortunately doesn't support searching of tweets using regular expressions which means that you do have to post process. There's not actually any official documentation from Twitter to that effect, but everyone who uses the Twitter search API post-processes their tweets using regex (including me).
On web, navigate to Settings and privacy > Your account > Account information. Once you enter your password, go to Request Verification. On Android and iOS, tap on Settings and Privacy > Account > Verification request. Please read the criteria below to understand if your account qualifies.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
The Validation (Regex) property helps you define a set of validation options for a given field. In general, this field property is used to perform validation checks (format, length, etc.) on the value that the user enters in a field. If the user enters a value that does not pass these checks, it will throw an error.
To validate if a string is a valid Twitter handle:
function validate_username($username)
{
return preg_match('/^[A-Za-z0-9_]{1,15}$/', $username);
}
If you are trying to match @username
within a string.
For example: RT @username: lorem ipsum @cjoudrey etc...
Use the following:
$string = 'RT @username: lorem ipsum @cjoudrey etc...';
preg_match_all('/@([A-Za-z0-9_]{1,15})/', $string, $usernames);
print_r($usernames);
You can use the latter with preg_replace_callback to linkify usernames in a string.
Edit: 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.
Edit (2): Here is a PHP port of the Twitter Text Library: https://github.com/mzsanford/twitter-text-php#readme
Don't use /
with ereg*
.
In fact, don't use ereg*
at all if you can avoid it. http://php.net/preg_match
edit: Note also that /[a-z0-9_]+/i
will match on spaces are invalid
and not-a-real-name
. You almost certainly want /^[a-z0-9_]+$/i
.
S
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With