How do I put extra number at the end of username if duplicate

前端 未结 8 1887
醉话见心
醉话见心 2021-01-19 23:31

Hard to explain, and let me show an example.

  1. If username foo already exists in MySQL I want php script will allow it but to be foo1
8条回答
  •  生来不讨喜
    2021-01-20 00:06

    First, use a regular expression to parse out the leading alpha part of the requested username, together with any trailing numeric suffix, something like:

    ^([a-zA-Z_]+)(\d)*$
    

    The first group gives you the stem (let's assign this to a variable called UsernameStem) and the second group gives you the number (let's assign this to UsernameNumber). Beware that the user may have not entered a numeric suffix, so you need to check for this special case and assign 0 to UsernameNumber.

    You can then issue a SQL statement on your users table as follows:

    SELECT MAX(username) FROM users WHERE username LIKE :UsernameStem || '%' 
    

    This will give you the existing username with the highest numeric suffix for the user's desired name.

    You can again use the regex above to parse out this maximum number - this time examine the second group returned by your regex match. You can then add 1 to this number to give the next available username.

    Example: the user request "foo21". The regex will parse out "foo" as the UsernameStem and "21" as the username number. Assuming that you have a user in your database with the username "foo44", the SQL query will return you this username. Applying the regex again to this username from your database will enable you to parse out the number "44". You can then convert this to an int, add 1, then concatenate this with your original UsernameStem. This will yield "foo45".

    Good luck!

提交回复
热议问题