正则表达式:在匹配中搜索

时间:2013-11-03 11:28:41

标签: php regex

这是来源:

<item>
  <title>Quarterly Report ( Third Quarter 2013 )</title>
  <link>http://www.example.com/reports/Q3 2013_Final.pdf</link>
  <pubDate>24 Oct 2013 00:00:00 +0500</pubDate>
</item>

我需要在网址中用%20替换空格。

我该如何去做?

编辑:源数据来自另一个我无法访问的网站,我不想仅仅为了替换空格字符而解析XML。

2 个答案:

答案 0 :(得分:1)

从您的评论中假设您使用的是php。

这个怎么样

function FixSpace($match)
{
    $out  = $match[1];                          // opening tag
    $out .= str_replace(' ', "%20", $match[2]); // url
    $out .= $match[3];                          // closing tag

    return $out;
}

$input = preg_replace_callback("~(<link>)(.*?)(</link>)~", "FixSpace", $input);

答案 1 :(得分:0)

首先使用正则表达式“。*&lt; / link&gt;”选择链接标记和内容然后替换空间I.e. \ s与%20

我用ruby langauge编写了一个例子。

str= "<item>

季度报告(2013年第三季度)   http://www.example.com/reports/Q3 2013_Final.pdf   2013年10月24日00:00:00 +0500 “     str.scan(/.*& LT; /链路&GT; /)first.gsub(/ \ S /, '%20')