duanbushi1867 2009-08-12 14:31
浏览 9
已采纳

如何修复这个正则表达式?

i have a regular expression to remove certain parts from a URI. However it doesn't take into account multiple parts in a way that works :-). Can somebody assist?

$regex = '~/{(.*?)}\*~'

$uri = '/user/{action}/{id}*/{subAction}*';
$newuri = preg_replace($regex, ''  , $uri); 

//$newuri = /user/
//Should be: $newuri = /user/{action}/

I know it matches the following part as one match:

/{action}/{id}/{subAction}

But it should match the following two seperately:

/{id}*

/{subAction}*

  • 写回答

1条回答 默认 最新

  • doulin4844 2009-08-12 14:37
    关注

    To me it looks like your {(.*?)}\* test is matching all of {action}/{id}*, which judging from what you've written isn't what you want.

    So change the Kleene closure to be less greedy:

    '~/{([^}]*)}\*~'
    

    But do you really need to capture the part inside the curly braces? Seems to me you could go with this one instead:

    '~/{[^}]*}\*~'
    

    Either way, the [^}]* part guarantees that the expression will not match {action}/ because it doesn't end in an asterisk.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?