开发者

Join 3 regular expressions in 1

everybody. Could you give me some suggestions on how I can jo开发者_运维问答in the following 3 regular expressions in 1?

preg_match_all('/>\s*([\w-]+)\s*</', $str, $matches_1);
preg_match_all('/<\?=\s*([\w-]+)\s*\?>/', $str, $matches_2);
preg_match_all('/echo\s*["|']+\s*([\w-]+)["|']+/', $str, $matches_3);

UPDATE

preg_match_all(
    '/
       >\s*([\w-]+)\s*<
       |
       <\?=\s*([\w-]+)\s*\?>
       |
       echo\s*("|')+\s*([\w-]+)("|')+
    /x',
    $str, $matches_123);

For me, the syntax above works only if written in one line and removing x-modifier. For some reason, not doing so causes:

Warning: preg_match_all() [function.preg-match-all]: Compilation failed: missing ) at offset 125 in ...

I've solved it by just splitting regex in 3 strings and concatenating them but it's a mess.


Join them as alternatives using |

preg_match_all(
    '/
       >\s*([\w-]+)\s*<
       |
       <\?=\s*([\w-]+)\s*\?>
       |
       echo\s*("|&\#039;)+\s*([\w-]+)("|&\#039;)+
    /x',
    $str, $matches_123);

You might want to enclose each part into ( parens ) to get them separated in the result list. But then the other subexpressions might need to be ?: prefixed. Also the alternatives ["|'] were invalid (square brackets don't work this way, might function by accident, but isn't a reliable match).


Depends what you mean by joining... Do you mean "match this, else that, else last"? If so:

/>\s*([\w-]+)\s*<|<\?=\s*([\w-]+)\s*\?>|echo\s*(?:"|')+\s*([\w-]+)(?:"|')+/
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜