【问题标题】:Try to preg_replace section of url to use as php variable尝试 preg_replace 部分 url 用作 php 变量
【发布时间】:2011-02-22 17:38:18
【问题描述】:

我们的网站在开头有这个调用来查找页面的名称(例如 product.html,product = name),并在其中添加“-tabs”以生成变量 $block_name:

    <? $current_url = $_SERVER['REQUEST_URI']; // this will return everything after the http://www.domain.xx including preceding "/"
$block_name = preg_replace ("/^(?:.*)\/(.*).html$/", "$1-tabs" , $current_url); ?>

该变量随后用于稍后调用静态块:

    <?php echo $this->getLayout()->createBlock('cms/block')->setBlockId($block_name)->toHtml() ?> 

如果有人转到http://example.com/product.html,它工作正常,但如果我使用任何 url 跟踪,如 Analytics,并且 url 末尾有这个:

http://example.com/product.html?utm_source=newsletter&utm_campaign=product_launch&utm_medium=email

然后变量没有正确创建并且静态块没有加载。

有没有办法忽略 .html 之后的任何内容,以便任何跟踪附加都不会影响静态块加载?

谢谢!

【问题讨论】:

    标签: php magento preg-replace


    【解决方案1】:

    preg_replace("/^(?:.*)\/(.*).html\??.*$/", "$1-tabs" , $current_url)

    【讨论】:

    • 谢谢,有效(之前的评论是因为我上传了错误的模板文件)
    【解决方案2】:

    我建议首先在该位置上使用parse_url,这将去掉 get 变量。从那里,您可以像现在一样操纵它。

    $pathOnly = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $block_name = preg_replace(...);
    

    【讨论】:

    • 试过这个但是不行,不知道Magento有没有自己的PHP_URL_PATH版本
    • @Rick:我实际上很喜欢另一个用户发布的内容,但似乎已被删除:$_SERVER['PHP_SELF']。试试REQUEST_URI 看看你是否有更好的运气。
    • 如果我需要它,我会记住它,但 nikhil500 的回答让它起作用了,干杯
    【解决方案3】:

    由于您使用的是 Magento 并且似乎是在模板中编写代码,因此您可以这样做:

    $_product = Mage::registry('product');
    if ($_product) $block_name = $_product->getUrlKey();
    

    产品页面上的多个模板已经为您定义了$_product,这让您更加轻松。

    当以非 SEO 方式请求页面时,例如“http://www.example.com/catalog/product/view/id/123/”,或者类别名称位于网址。 $_SERVER 无法处理这些情况。使用来自 $_SERVER 的未经验证的值允许攻击者将值插入到您的代码中,这绝对是不好的。

    【讨论】:

    • 感谢 Magento 的具体回复。尝试使用代码,是的,产品页面已经定义,我有:&lt;? $_helper = $this-&gt;helper('catalog/output'); $_product = $this-&gt;getProduct(); if ($_product) $block_name = $_product-&gt;getUrlKey(); $block_name = preg_replace ("/^(?:.*)\/(.*).html$/", "$1-tabs" , $current_url); ?&gt; 但是当我将 ?xxxx 添加到 url 的末尾时,静态块部分不会 loa
    • 我的意思是,你不需要$current_url,也不需要preg_replace,也不需要检查.html。 URL 密钥正是您在管理员中为产品输入的内容,并且没有尾随 .html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2010-12-16
    • 1970-01-01
    • 2010-11-26
    • 2016-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多