【问题标题】:Replace string or explode() function [duplicate]替换字符串或explode()函数[重复]
【发布时间】:2013-10-05 16:18:11
【问题描述】:

我有一个格式如

的链接
http://example.com/a/b.swf

我想把它转换成

http://cache.example.com/a/b.swf

我该怎么做?

我尝试使用 PHP 的 explode() 函数,但是当我分解字符串的某些部分时,我将它添加到自身中它不起作用。

【问题讨论】:

  • 请出示您已有的代码。
  • 不要explode() url,而是使用函数parse_url()

标签: php string replace str-replace


【解决方案1】:
$new_string = str_replace('http://example.com/', 'http://cache.example.com/', $orig_string);

?

【讨论】:

  • 但是值动态地来自一个变量?
  • $new_string = str_replace(array_keys($map), array_values($map), $orig_string); if $map=array('example.com/'=>'http://cache.example.com/',...);
  • 当你用 http... 替换完整的字符串时,如果有参数,它就相等。
【解决方案2】:

如果你想更“专业”,那就用一个特殊的函数http://php.net/manual/en/function.parse-url.php解析网址吧。

【讨论】:

    【解决方案3】:
    $str = 'http://example.com/a/b.swf';
    $str = str_replace('http://', 'http://cache.', $str);
    

    【讨论】:

      【解决方案4】:

      试试str_replacestr_replace ($search , $replace , $subject [, int &$count ])

      $str = 'http://example.com/a/b.swf';
      $substr = 'http://';
      $attachment = 'cache.';
      
      $newstring = str_replace($substr, $substr.$attachment, $str);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-20
        • 2012-07-23
        • 2016-06-06
        • 1970-01-01
        • 1970-01-01
        • 2011-10-10
        • 2019-01-14
        • 1970-01-01
        相关资源
        最近更新 更多