in twitter
when you write @moustafa
will change to <a href='user/moustafa'>@moustafa</a>
now i want make the same thing
when write @moustafa + space its change @moustafa only
views:
83answers:
5You're looking for a regular expression that matches @username, where username doesn't have a space? You can use:
@[^ ]+
If you know the allowed characters in a username you can be more specific, like if they have to be alphanumeric:
@[A-Za-z0-9]+
Why not use the @anywhere javascript library that Twitter have recently released?
Regular Expressions in PHP are just Strings that start and end with the same character. By convention this character is /
So you can use something like this as an argument to any of the many php regular expression functions:
Not space:
"/[^ ]+/"
Alphanumeric only:
"/[A-Za-z0-9]+/"
One regular expression that could be used (shamelessly stolen from the @anywhere javascript library mentioned in another answer) would be:
\B\@([a-zA-Z0-9_]{1,20})
This looks for a non–word-boundary (to prevent a@b
[i.e. emails] from matching) followed by @
, then between one and 20 (inclusive) characters in that character class. Of course, the anything-except-space route, as in other answers; it depends very much on what values are to be (dis)allowed in the label part of the @label
.
To use the highlighted regex in PHP, something like the following could be used to replace a string $subject
.
$subject = 'Hello, @moustafa how are you today?';
echo preg_replace('/\B\@([a-zA-Z0-9_]{1,20})/', '<a href="user/$1">$0</a>', $subject);
The above outputs something like:
Hello, <a href="user/moustafa">@moustafa</a> how are you today?
There are several libraries that perform this selection and linking for you. Currently I know of Java, Ruby, and PHP libraries under mzsanford's Github account: http://github.com/mzsanford/twitter-text-rb