I don't think there's any straight answer to this! It depends on what visa you're on and what visa you're partner is on.
For instance, you need to have at least three months left on your visa to apply for a Certificate of Approval from Home Office (which you MUST have to get married here because you're on some kind of visa). Your partner if he/she is on a visa, will need one too. A COA takes about 6-8 weeks to get.
Once you get the COA you then have to lodge a regular notice of marriage at your local register office and then wait a further 16 days before you can legally marry.
The thing to remember is that your COA does not mean you have the right to stay in the UK as a dependent of your spouse once you are married. Once married, you will then need to apply for a spousal visa and the way this works will depend on what visa you and your partner are on. Ie, if you're partner has a British passport you can apply from the UK, but if he/she doesn't have a passport and is on a visa you'll need to return home to apply.
I'm not sure this answers your question, but I hope it helps a bit.
Good luck!