[英]IF statement to check url in PHP with RegEx
I would like to change the language of my content on my search results template.我想更改搜索结果模板上内容的语言。 Since the Spanish versions of each page are in a sub-directory
/es/
I have been able to successfully manage content with Javascript using some simple RegEx.由于每个页面的西班牙语版本都在子目录
/es/
我已经能够使用一些简单的 RegEx 使用 Javascript 成功管理内容。 However, this template is in a .php
file.但是,此模板位于
.php
文件中。 How can I check to see if the page is in the /es/
sub-directory?如何检查页面是否在
/es/
子目录中?
Here is my initial thinking (obvious syntax issue, just tried to get structure going):这是我的初步想法(明显的语法问题,只是试图让结构正常运行):
<?php
$spanishPage = "/.*\/es\//";
if (preg_match($spanishPage, $_SERVER['REQUEST_URI'])) { ?>
<h2>Spanish results for: <span><?php the_search_query(); ?></span></h2>
<?php
}
else { ?>
<h2>English results for: <span><?php the_search_query(); ?></span></h2>
<?php
} ?>
Using strpos:使用 strpos:
<?php
$spanishPage = "/.*\/es\//";
if (strpos($_SERVER['REQUEST_URI'], $spanishPage)) {
echo 'This is spanish page';
}
else {
echo 'this is an english page';
}
?>
The slashes in $spanishPage
are for regular expressions, strpos doesn't use them $spanishPage
中的斜杠用于正则表达式,strpos 不使用它们
<?php
// a regular expression that will get a language code out of a URL
$regEx = '#/(\w\w)/(.*)$#';
// use the regex with the request URL
if(preg_match_all($regEx,'https://www.example.com/es/my-page.php',$matches)) {
if (is_dir($matches[1][0])) {
echo 'Directory is '.$matches[1][0].PHP_EOL;
echo 'Page is '.$matches[2][0];
if (!is_file($matches[2][0])) {
echo ' not found';
}
} else {
echo 'Directory '.$matches[1][0].' doesn\'t exist'.PHP_EOL;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.