简体   繁体   English

用于匹配所有的PHP正则表达式模式

[英]PHP regex pattern for matching all

I have a-facebook-like mentioning feature in my app. 我的应用程序中有一个类似facebook的提及功能。

When creating posts or comments user can mention other users with @ sign. 在创建帖子或评论时,用户可以使用@符号提及其他用户。 I use following jQuery plugin: http://podio.github.com/jquery-mentions-input/ 我使用以下jQuery插件: http//podio.github.com/jquery-mentions-input/

Mentions are generated in the following format: @@[Marko Kurjonen:2] so "@@[User's name:user_id] 提及的格式如下:@@ [Marko Kurjonen:2] so“@@ [User name's name:user_id]

Currently I have following pattern (and code): 目前我有以下模式(和代码):

$pattern = "/@@\[(.*):(\d*)] /ims";

$matches = array();
preg_match_all($pattern, $input, $matches);
Zend_Debug::dump($matches);
$output = preg_replace($pattern, "<a href=\"". $this->view->baseUrl("user") ."/$2\" class=\"tooltip\">$1</a>", $input);

Problem is that it only does the first mention. 问题是它只是第一次提到。

Example string: 示例字符串:

$input = "Hello @@[Markku Pelkonen:7] and @@[Marko Kurjonen:2]"

Only first user gets converted by preg_replace. 只有第一个用户被preg_replace转换。

br, Marko br,马可

You can use this regex: 你可以使用这个正则表达式:

/@@\[([^:]*):(\d*)\]/

This regex assumes that the name doesn't contain : character. 此正则表达式假定名称不包含:字符。

The original regex has 2 problems: 原始正则表达式有两个问题:

  • The space at the end, just after ] , causes the second mention to fail to match, since it is at the end of the input. 最后的空间,刚好在]之后,导致第二次提及无法匹配,因为它位于输入的末尾。 (If you remove it, the greedy quantifier will gobble up the whole input string.) (如果你删除它,贪婪的量词将吞噬整个输入字符串。)
  • The * in (.*) matches 0 or more instances greedily , which means it will match as many character as possible until the next token cannot match, where it will backtrack and try to match the next token. * in (.*) 贪婪地匹配0个或更多实例,这意味着它将匹配尽可能多的字符,直到下一个令牌无法匹配,它将回溯并尝试匹配下一个令牌。 This is why the whole input string will be gobbled up if you remove the space, as mentioned above. 这就是为什么如果你移除空间,整个输入字符串将被吞噬,如上所述。

It is also possible to fix your regex a bit to make it work (apart from the solution I mentioned above): 也可以修改你的正则表达式使它工作(除了我上面提到的解决方案):

/@@\[(.*?):(\d*)]/s

The m flag and i flag are useless here, so I remove them. m标志和i标志在这里没用,所以我删除了它们。 You never use ^ or $ in your regex, so m flag is useless. 你永远不会在你的正则表达式中使用^$ ,所以m标志是没用的。 The i flag is only useful if there are letter in the regex , which is not the case here. 只有正则表达式中有字母时 i标志才有用,这不是这里的情况。

I use *? 我用*? quantifier here, which is the lazy version of match 0 or more. 这里是量词,这是匹配0或更多的懒惰版本。 It will match as few character as possible just for the next token to be matched. 它将匹配尽可能少的字符,仅用于匹配的下一个标记。

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

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