简体   繁体   English

如何将第二次出现的字符与正则表达式匹配?

[英]How can I match the second occurrence of a character with a regular expression?

I'm trying to match the second forward-slash in a relative URL. 我正在尝试在相对URL中匹配第二个正斜杠。

/dir/entry

I want to match the / following dir . 我想匹配/后面的dir

如果您试图分解路径中的目录,将正则表达式保留在工具箱中并使用explode()可能是有意义的。

$parts = explode( '/', $path );

Since there is no significance about the / , I assume you want to find out the position. 由于/意义不大,因此我假设您想找出位置。 You can do it with the fourth parameter of preg_match_all : 您可以使用preg_match_all的第四个参数来实现:

preg_match_all('~/~', $input, $matches, PREG_OFFSET_CAPTURE);
$pos = $matches[0][1][1];

The indexing into $matches is quite horrible, though. 不过,将索引$matches$matches是非常可怕的。 The first index corresponds to the capture. 第一个索引对应于捕获。 0 is the whole match, 1 , 2 , 3 and so on would be the results of capturing groups (sets of parentheses inside the pattern), which you don't have here. 0是整场比赛, 123等将捕获组(图案内套括号),这你不用在这里的结果。 The second index corresponds to the match. 第二个索引对应于匹配项。 You want the second match, so you want to go for index 1 . 您需要第二场比赛,因此您想获得索引1 The last index is 0 for the actually matched/captured string and 1 for the match's/capture's offset. 最后一个指标是0的实际匹配/捕获字符串和1对比赛的/捕获的偏移。

Do you want to match the second slash and nothing else? 您是否要匹配第二个斜杠,别无其他? Try this: 尝试这个:

preg_match('~^/[^/]+\K/~', '/dir/entry');

\\K is the MATCH POINT RESET construct: when it's encountered, the regex engine "forgets" whatever characters it's seen so far, and acts like the current match position is the beginning of the match. \\KMATCH POINT RESET构造:遇到它时,正则表达式引擎“忘记”到目前为止所看到的任何字符,其行为就像是当前比赛的位置是比赛的开始。 For example, if you wanted to replace the second slash with @ , you would normally do this: 例如,如果要用@替换第二个斜杠,通常可以这样做:

preg_replace('~^(/[^/]+)/~', '$1@', '/dir/entry');  # /dir@entry

But if you're in a situation where you can't use a capturing group, \\K will set you right: 但是,如果您无法使用捕获组,则\\K将设置正确:

preg_replace('~^/[^/]+\K/~', '@', '/dir/entry');  # /dir@entry

\\K is only supported in Perl and PHP that I know of. \\K我所知,仅在Perl和PHP中支持\\K

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM