Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php: What good syntax for integrating a variable into regex

For a multilingual website I want to detect existence of region code (fr, en, es, etc) inside url.
The goal is to add region code for each url that doesn’t have yet one , for example : https://subdomain.domain.com/fr.

To do I use wp_safe_redirect() function and this condition which works:

if(preg_match ("/^(?:(?!fr).)*$/i", $_SERVER['REQUEST_URI'])){
   wp_safe_redirect($addlang.'/'.$currentpage);
}

This condition is used to redirect to language from $_SERVER[‘REMOTE_ADDR’] so I need to insert variable ‘.$visitorlang.’ instead of "fr", but this syntax is refused.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$visitorlang = "result-of-get.geojs.io";
"/^(?:(?!'.$visitorlang.').)*$/i"

I also tried {$var} but doesn’t work .

Also I will use a powerful regex to detect two char at the beginning of $_SERVER[‘REQUEST_URI’] instead of the region code but one more time this syntaxe is not accepted :

"/^(?:(?![a-z]{2}).)*$/i"

Also is there a special syntaxe to include "|" (OR) to detect only allowed languages : "fr|en|es".

>Solution :

You don’t need the quotes and .. Variables are automatically substituted inside double-quoted strings.

if(preg_match ("/^(?:(?!$visitorlang).)*$/i", $_SERVER['REQUEST_URI'])){
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading