At the moment I am working very hard on translating my Islam Archive project. Now I was faced with a problem, which is a very interesting thing but not necessarily conclusive.
The problem
My translations are saved as strings and now the user should receive an e-mail as soon as he has successfully registered. But how do you put a variable into an existing in php?
Problem example
It should be in the mail, for example: You have successfully registered. Please log in with the e-mail address mail@mailprovider.com.
If this is my string, how do I use the e-mail address?
The solution
For this, php offers a simple solution. There are the built-in functions:
- printf (string, var1, var2, var3, …)
- sprintf (string, var1, var2, var3, …)
- vprintf (string, array)
- svprintf (string, array)
I was just totally confused what that means at all but came very quickly to a solution.
All functions do the same job. They take a string and search it for placeholders. If these placeholders are found, they are replaced with the variables passed in the following arguments.
A solution example
$email_text = 'You have successfully registered with the email address %s. Please click <a href=\"%s\">here</a> to activate your account.';
$mail = sprintf(
$translations->login_register->registered_mail,
'info@talhasariyuerek.com',
'https://www.talhasariyuerek.com/activate/da39a3ee5e6b4b0d3255bfef95601890afd80709'
);
/*
Ergebnis:
You have successfully registered with the email address info@talhasariyuerek.com. Please click <a href="https://www.talhasariyuerek.com/activate/da39a3ee5e6b4b0d3255bfef95601890afd80709">here</a> to activate your account.
*/
Where are the differences?
With s and without s
You have probably already noticed that there is once the function itself and once the variant with the letter “s” in front of it. This letter is just for silent. If you use the functions printf or vprintf, the result is echoed directly. However, if you use the function sprintf or svprintf, the result will be returned and you can use the variable in another function.
sprintf and svprintf
These two functions also don’t have a serious difference. The only thing is that with sprintf you pass all strings as arguments and with vsprintf you just put all the strings in an array.
Depending on in which format you have the needed strings, you can use the appropriate function.
Conclusion
I’ve already seen a lot of use in these functions and am using them. It’s not complicated either and I’m grateful that the php community has built in these features. I hope that I’ve helped you with this post and if you still have questions, you can send them to me via the email address info@talhasariyuerek.com . I will answer them as soon as possible.