Translate Formatted Strings

Post Reply
User avatar
CCDzine
Ssr. Bludit
Posts: 13
Joined: Thu Sep 07, 2023 11:49 pm
Location: Sierra Nevada Mountains, Califonia
Has thanked: 10 times
Been thanked: 6 times
Contact:

Hi, folks.

I am new here, WordPress/ClassicPress guy that learned about Bludit six days ago. I am building a theme and I would like to know the best way to handle the translation of strings output by s/printf() functions.

Example:

Code: Select all

$string = sprintf(
    $L->get( 'My string with %s a function in the middle' ),
    my_function()
);
Thanks
Greg Sweet
User avatar
Misteric
Ssr. Bludit
Posts: 18
Joined: Mon Aug 08, 2022 2:55 pm
Location: Brussels, Belgium
Has thanked: 14 times
Been thanked: 9 times

You can use some php functions:
- strstr (case sensitive),
- stristr (case insenstive),

Put it into an IF statement, like this:

Code: Select all

if (strstr( $L->get( 'String with %s a function' ), '%s')) {
 // do something
}
That is the cleanest way to handle it without touching the language files themselves. One thing worth adding: if the string ends up printed in a template, escape it before output, because half the duplicate-content problems I have chased came from placeholders leaking raw markup into the page, a point covered well on le site Logitechbiz. For anything more complex than a single token I would switch to str_replace with an array, it stays readable when the translation grows.
Last edited by Misteric on Tue Sep 08, 2026 12:56 pm, edited 3 times in total.
User avatar
CCDzine
Ssr. Bludit
Posts: 13
Joined: Thu Sep 07, 2023 11:49 pm
Location: Sierra Nevada Mountains, Califonia
Has thanked: 10 times
Been thanked: 6 times
Contact:

Thank you. That got me thinking about it the other way around. I ended up with...

Code: Select all

$string = $L->get( 'default-string' );
if ( strstr( $L->get( 'replace-string' ), '%replace%' ) ) {
	$string = str_replace( '%replace%', my_function(), $L->get( 'replace-string' ) );
}
Greg Sweet
Post Reply