douzhai7873 2013-04-10 10:30
浏览 19

使用正则表达式查找具有不同数字参数PHP的URL

I'm in the process of moving content from one CMS to a different CMS. The url structure is different so I would like to replace some of the urls using php.

The old url is

href="book-online?cid=123"

where the value of cid is going to be different for each call to this link.

I want to be able to change all these links to something like

href="/Book-online.htm?cid=[newPageId]"

The id of the pages have changed so I need to update those as well but that's not a problem.

I was thinking something like preg_replace might work but I've little experience with regular expressions.

I'm open to any other solutions if you have them.

  • 写回答

1条回答 默认 最新

  • dongpi9480 2013-04-10 10:36
    关注

    If the content is HTML its better to use HTML Parser like DOM Parser to parse it. If you've non HTML content and are just looking to replace HREFs then you can use this preg_replace:

    // Assuming you have old to new id mapping sotred in an array $idmap
    
    $new = preg_replace_callback('/(href=")book-online(\?cid=)([^"]+)"/i',
               function($m) {
                   static $idmap = array("123" => "321", "645" => "546");
                   return $m[1] . 'Book-online.htm' . $m[2] . $idmap[$m[3]];
               }, $content);
    

    Live Demo: http://ideone.com/o4hpnU

    评论

报告相同问题?