phpregexreplacepreg-replace

Support needed for preg_replace to detect language tag and remove other language data


I have a data string which contains 3 different language content enclosed in corresponding tags.

/[langStart-en] and //[langEnd-en] for English

/[langStart-ar] and //[langEnd-ar] for Arabic

/[langStart-fr] and //[langEnd-fr] for French

A language code will be passed as parameter through the url, say for eg. if the language is English, the url will be

article.php?lang = EN,

for Arabic article.php?lang = AR and

for French article.php?lang = FR.

I want to detect the Language and remove the contents for other languages from the string.

Hope this make sense


Solution

  • I have a quick solution for you. Please check if it works.. You should be able to optimize the logic, but I hope this will help you to make it working.

    $pattern1 = '/\/\/\[langStart-en\][^n]*\/\/\[langEnd-en\]/';
    $pattern2 = '/\/\/\[langStart-ar\][^n]*\/\/\[langEnd-ar\]/';
    $pattern3 = '/\/\/\[langStart-fr\][^n]*\/\/\[langEnd-fr\]/';
    
    $lan= $_GET['lang'];
    $replace= '';
    $string = "whatever may be string";
    
    if ($lan=='EN')
    {
    $string = preg_replace($pattern2, $replace, $string);
    $string = preg_replace($pattern3, $replace, $string);
    
    }
    
    else if ($lan=='AR')
    {
    $string = preg_replace($pattern1, $replace, $string);
    $string = preg_replace($pattern3, $replace, $string);
    
    }
    
    else if ($lan=='FR')
    {
    $string = preg_replace($pattern1, $replace, $string);
    $string = preg_replace($pattern2, $replace, $string);
    }
    echo $string;
    

    Please check and let me know if you find any issues.