匹配[php]代码[/php]的正则表达式
作为项目的一部分,我需要以以下方式分析可能包含对PHP引用的字符串:匹配[php]代码[/php]的正则表达式,php,regex,Php,Regex,作为项目的一部分,我需要以以下方式分析可能包含对PHP引用的字符串: [php]函数名(args1,args2)[/php] 函数名并不总是相同的,我想用另一个值替换上面示例中的所有内容(包括伪标记) 谁能推荐一个正则表达式来有效地匹配模式[php]任何东西[/php] 抱歉,如果这是一个基本的问题,但我在正则表达式方面很差劲 我认为“\[php\](.*?\[\/php\]””可以解决这个问题 编辑:您可能需要也可能不需要双引号——不确定最终如何使用正则表达式字符串 尝试使用 \[php\](
[php]函数名(args1,args2)[/php]
函数名并不总是相同的,我想用另一个值替换上面示例中的所有内容(包括伪标记)
谁能推荐一个正则表达式来有效地匹配模式[php]任何东西[/php]
抱歉,如果这是一个基本的问题,但我在正则表达式方面很差劲 我认为“\[php\](.*?\[\/php\]””
可以解决这个问题
编辑:您可能需要也可能不需要双引号——不确定最终如何使用正则表达式字符串 尝试使用
\[php\](.*)\[\/php\]
如果不允许使用
[php]
、[/*comment/*php]
(或其他疯狂的东西)之类的结构,则可以使用以下方法:
/\[php\](.*?)\[\/php\]/
第一个匹配的组将是标记内的文本。我认为正则表达式非常直观,除了
?
:它将是惰性的,只在第一个结束标记之前匹配文本,因此如果您有[php]…[/php][php]…[/php]
,正则表达式将不匹配..[/php][php]…
(即在第一个[php]
和第二个[/php]
之间)如果您使用的是WordPress,请务必查看短代码API
如果不考虑抓取它的代码。它的编写是为了可以在任何应用程序中使用。
您可以搜索这些标记之间的字符串,例如\[PHP\](.+[^\b\[])\[/PHP\]
试试这个:
$start_tag ='\\\\[php\\\\]\\\\s*';
$function ='((\\\\w+)\\\\s*\\\\(([^)]*)\\\\)';
$end_tag ='\\\\s*\\\\[\\\\/php\\\\]';
$re='/(' . $start_tag . $function . $end_tag . ')/';
即:
( # start capture group #1 - full match
\[ # literal '['
php # literal 'php'
\] # literal ']'
\s* # optional whitespace
( # start capture group #2 - full function
( # start capture group #3 - function name
\w+ # one or more word chars [A-Za-z0-9_]
) # end capture group #3
\( # literal '('
( # start capture group #4 - function arguments
[^)]* # zero or more non-')' chars
) # end capture group #4
\) # literal ')'
) # end capture group #2
\s* # optional whitespace
\[ # literal '['
php # literal 'php'
\] # literal ']'
) # end capture group #1
另请参见:这有助于创建相应的匹配模式。您的目的是匹配开始和结束伪标记之间的任何内容还是仅匹配PHP函数调用?不必担心。对于额外的解释/信息,您的答案中肯定有+1。由于OP希望替换整个模式,因此不需要捕获。“PHP”不应该是“PHP”来匹配OP的标准吗?-1因为您的解决方案将无法匹配“[PHP]f(a,b)[/PHP]”,因为“,”和空格都是单词边界。请注意,“\w+”和“[^]”*'必须是非贪婪的('lazy'),因为它们都被后面的字符所限制。因为PHP禁止标识符以数字开头,所以将'\w+'更改为'[a-Za-z]\w*',以只匹配合法的函数名。那么
[PHP]func($somearray[0])[/PHP]
呢?
( # start capture group #1 - full match
\[ # literal '['
php # literal 'php'
\] # literal ']'
\s* # optional whitespace
( # start capture group #2 - full function
( # start capture group #3 - function name
\w+ # one or more word chars [A-Za-z0-9_]
) # end capture group #3
\( # literal '('
( # start capture group #4 - function arguments
[^)]* # zero or more non-')' chars
) # end capture group #4
\) # literal ')'
) # end capture group #2
\s* # optional whitespace
\[ # literal '['
php # literal 'php'
\] # literal ']'
) # end capture group #1