开发者

Regular expression to convert usernames into links like Twitter does

开发者 https://www.devze.com 2022-12-27 21:04 出处:网络
in twitter when you write @moustafa will change to <a href=\'user/moustafa\'>@moustafa</a> now i want make the same thing

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 it开发者_开发问答s change @moustafa only


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?


You'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]+


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]+/"


Why not use the @anywhere javascript library that Twitter have recently released?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号