【问题标题】:php- replace a string within a stringphp-替换字符串中的字符串
【发布时间】:2013-11-05 19:09:25
【问题描述】:

您好,我有以下搜索表单:

<form method='get'><input type='text' name='searchvalue' value='<? if (isset($_GET['searchvalue'])) echo $_GET['searchvalue'];?>' />&nbsp;<input type='submit' value='Search' /><input type='hidden' name='pagenum' value='1' /></form>

它是访问API并返回搜索结果的wordpress插件的一部分,当我将搜索数据发送到api时,file_get_contents("$api_url/book/index.php/name/$searchvalue?key=$api_key");查询,如果它有空格,需要这样格式化:This%20Is%20An%20Example相反,它的格式如下:This+Is+An+Example

我打算使用str_replace() 替换加号:str_replace("+", "%20", $searchvalue);,但它似乎不起作用!

有什么建议吗?

【问题讨论】:

    标签: php string wordpress search replace


    【解决方案1】:

    使用 rawurlencode() 函数。

    $searchvalue = rawurlencode($searchvalue);
    

    这将解决您的问题。

    【讨论】:

      【解决方案2】:

      尝试如下:

      file_get_contents("$api_url/book/index.php/name/".rawurlencode($searchvalue)."?key=$api_key");

      查看文档:http://www.php.net/manual/en/function.rawurlencode.php

      一些通用的url函数:http://php.net/manual/en/ref.url.php

      【讨论】:

        【解决方案3】:

        $searchvalue = str_replace('+', '%20', $searchvalue); 可以解决问题。

        http://www.php.net/manual/en/function.str-replace.php

        【讨论】:

          【解决方案4】:
          1. 根据文档,链接到 Casimir et Hippolyte 提到的 PHP 手册,第一个参数是搜索字符串,在您的情况下为 '+',第二个参数是搜索将被替换的字符串,在您的情况下为 '% 20'。所以你的命令似乎是正确的。

          2. 但请确保您将函数值的返回值分配给变量,因为 str_replace 不会像对象上的方法那样更改给定的字符串值。它是函数,它“仅”将更改后的字符串作为值返回。

          除了以下事实:

          • 手动修改 WP 插件通常不是一个好主意
          • 带有插件的 WP 是一个非常复杂的系统,有时很难解读所有执行代码的操作。尽可能总是在类似的情况下测试最少,有问题的部分代码由 WordPress 分开。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-02-20
            • 1970-01-01
            • 1970-01-01
            • 2014-03-06
            • 2012-05-13
            • 1970-01-01
            相关资源
            最近更新 更多