【问题标题】:IF statement to check url in PHP with RegExIF 语句使用 RegEx 检查 PHP 中的 url
【发布时间】:2021-02-13 06:05:03
【问题描述】:

我想更改搜索结果模板中内容的语言。由于每个页面的西班牙语版本都在子目录/es/ 中,我已经能够使用一些简单的正则表达式成功地使用 Javascript 管理内容。但是,此模板位于 .php 文件中。如何查看页面是否在/es/ 子目录中?

这是我最初的想法(明显的语法问题,只是试图让结构继续下去):

<?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
    } ?>

使用 strpos:

<?php 
                            $spanishPage = "/.*\/es\//"; 
                            if (strpos($_SERVER['REQUEST_URI'], $spanishPage)) {
                                echo 'This is spanish page';
                            }
                            else {
                                echo 'this is an english page';
                            }
                        ?>

【问题讨论】:

  • 去掉g标志,PHP正则表达式不支持这个标志。
  • @wiktor - 好的,我已经删除了,现在看起来正确吗?
  • 我建议您阅读strpospreg_match 上的文档以了解预期的参数,然后选择其中一个来使用。
  • @miken32 这是我卡住的地方,我想preg_match 更接近我的需要,我已经更新了上面的代码,任何帮助都会很棒
  • 这是一个简单的子串搜索;事情没有变得更基本。一目了然,你所拥有的应该可以工作。不过,strpos 完全可以满足如此简单的搜索需求。

标签: php regex wordpress


【解决方案1】:

$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;
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 2012-09-17
    • 1970-01-01
    • 2015-03-13
    • 2013-04-09
    • 1970-01-01
    相关资源
    最近更新 更多