Best way to REPLACE with MySQL for usernames
I'm developing a site in PHP and it's setup with its own status and wall system right now (similar to twitter and facebook, respectively). I'm trying to make it so a user can change his username later on and any statuses or wall posts that mention the user (as in "@woo hi!") will be replaced with the new username.
I've tried using the REPLACE query in MySQL, but obviously I can't just replace 'username' with 'newusername', because if someone with the username of @w changed their username to @f, then some开发者_Go百科one else's account with the username @woo will become @foo. Get my drift?
I think my option is to basically create my own format to save the statuses/wall posts in that replace the username @woo with the |woo| (or anything that denotes an ending of the username), but I was curious if someone else had a different idea on the matter, or if someone knew about making the REPLACE query do this for me (like a way to make it scan as whole words, so that way @w != @woo. I'd love to hear what you think.
EDIT:
I figured out what I'm gonna do and am updating this for anyone else's future reference. I decided to replace all @usernames in statuses/wall posts with #@usernames# and save them like that in the DB. So now I can use a simple REPLACE query with MySQL to replace all the username mentions in statuses/wall posts, and won't have ambiguity problems (@w turns into #@w# in my database, which means that changing the username @w (#@w#) to @f (#@f#) won't change #@woo# to #@foo#. Of course when displaying the usernames in posts now, I have to run the content through an "unformat" function with strips the # at the start and end, but that's not too bad.
You could design your database to store additional data about each status/posts, for example, a list of all user ids for users mentioned in the post. Then, it would be easy to execute a targeted search and replace by:
- Locating all posts that mention a user changing their name by joining on their id
- Replacing
$oldname
with$newname
in only those posts
You may still have a small margin of ambiguity (multiple mentions in a single post), but you should be able to write a regular expression that identifies $oldname
and not a substring of $oldname
.
精彩评论