phpregexwordpresspreg-replaceqtranslate-x

Wordpress How can I programmatically update post name for a certain language using qTranslateX Plugin


I'm using qTranslateX plugin for my multi-language Wordpress Website. I have set 2 languages: en & fr. I was wondering how can I update a post name programmatically ONLY for a specific language? I searched everywhere and I did not find a solutions.

A workaround was to use a preg_replace function, which looks like this (Let's say the post name is: My [en]English[fr]French[:] post name )

$start = '\[en\]';
$end  = '\[';
$original_name = 'My [en]English[fr]French[:] post name';
$replace_with = 'Awsome english new';
$new_post_name = preg_replace('#('.$start.')(.*)('.$end.')#si', '$1'.$replace_with.'$3', $original_name ,1);
echo $new_post_name ;

This outputs the following incorrect string because the french text is deleted, so the preg_replace is not limiting on the first occurrence:

My [en]Awsome english new[:] post name

The expected output is:

My [en]Awsome english new[fr]French[:] post name

I'm kinda stuck here...


Solution

  • Make the part to be replaced non greedy:

    $new_post_name = preg_replace('#('.$start.')(.*?)('.$end.')#si', '$1'.$replace_with.'$3', $original_name ,1);
    //                                      here __^