开发者

preg_match and preg_replace question

I am creating dynamic XML and need to update the lastBuildDate in a file on my server. I know how to do everything but change that.

I figured I could use preg_match to look for the expression and preg_replace to replace it. My string will look like this:

$buil开发者_运维技巧d_date = '<lastBuildDate>Fri 16 Sep 2011 2:30:15 -6:00 GMT<lastBuildDate>';

How do I use preg_match to find the date inside the tags and then how do I replace it? I'm a noob when it comes to regular expressions, which is what I think I have to use. I'm just not sure how to find a wildcard inside that string.

Thanks.


What I advise you to do is read the preg_match and PCRE syntax documentation, then use a tool such as RegExr which will explain the regex you are writing with English words. It's a great tool to begin with.


At first glance I think you're missing a '/' on your close tag. I'll assume there is supposed to be one.

Like what others have already commented, you should be using an XML parser.

But, to answer how to do this w/ preg_replace, you could do this:

$build_date = "<lastBuildDate>Fri 16 Sep 2011 2:30:15 -6:00 GMT</lastBuildDate>";

function replacer($matched) {
    return "<lastBuildDate>" . strrev($matched) . "</lastBuildDate>";
}

echo preg_replace("/<lastBuildDate>(.*?)<\/lastBuildDate>/me", "replacer('$1')", $build_date);

This will echo the xml tag, where (for the sake of example) the date string is simply reversed. Again, I'd advise against using an expression to do this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜