I've been using stackoverflow to learn a lot about both PHP and JS (incl jquery) so I tend to google all the time but I didn't find an exact reply to this question
I have many strings with words mixed with numbers, like:
"60 reviews from 12 people, 20% of users"
This is an example but it can be much more complex ("word_one 45 word_two word_three 657 word_four 32% word_five USD20")
The use is content localisation:
I want to retrieve the numbers and save them into an array -> done
I want to match these numbers with what I already have in the database, i.e. if I have
en: "2 reviews from 2 people, 2% of users"
es: "2 comentarios de 2 personas, el 2% de los usuarios" -> done too
Now what I want to do is to replace the numbers in the matching string extracted from the database (all of them are "2" because I saved them this way, to avoid the plural-singular problem) with the numbers from the original string in English. Example:
I have this in English:
"60 reviews from 12 people, 20% of users"
I have this in the database:
en: "2 reviews from 2 people, 2% of users"
es: "2 comentarios de 2 personas, el 2% de los usuarios"
I want this in Spanish:
"60 comentarios de 12 personas, el 20% de los usuarios"
Code:
$pattern = '!\d+!';
$repv = preg_replace($pattern, "2", $v);
preg_match_all($pattern, $v, $matches);
$matchesnb = count($matches, 1);
$pattarray = array_fill("0", "1", array_fill("0", ($matchesnb-1), $pattern));
$reptarget = preg_replace($pattarray, $matches, $dbdata[1]);
Thanks a lot in advance!!
Why don't you save your template sentences in your database ready to be used with the sprintf()
function?
$str = array(
'en' => '%d reviews from %d people, %01.1f%% of users',
'es' => '%d comentarios de %d personas, el %01.1f%% de los usuarios'
);
$res = sprintf($str['es'],60,12,20);
$str = array(
'en' => '%1$d reviews from %2$d people, %3$01.1f%% of users',
'es' => '%1$d comentarios de %2$d personas, el %3$01.1f%% de los usuarios',
'tr' => '%2$d kullanıcıdan %1$d yorum, tüm kullanıcıların %%%3$01.1f\'si'
);
$res = sprintf($str['es'],60,12,20);