As part of a project, I need to analyse string which may contain a reference to PHP in the following manner:
[php]functionName(args1, args2)[/php]
The function name is not always the same, and I would like to replace everything in the above example (including the pseudo-tags) with another value.
Can anyone suggest a Regular Expression to effectively match the pattern [php]anything[/php]
.
Sorry if this is a basic开发者_JS百科 question, but I suck at Regular Expressions!
I think "\[php\](.*?)\[\/php\]"
would do the trick.
Edit: you may or may not need the double quotes-- not sure how you're ultimately using the regex string.
<?php
$s = "Lorem ipsum dolor sit amet, [php]functionName(args1, args2)[/php] ok.";
echo preg_replace("/\[php\][^\[]+\[\/php\]/", "seems to work", $s) . "\n";
// prints => Lorem ipsum dolor sit amet, seems to work ok.
?>
If constructs like [ php ]
, [/*comment/*php]
(or other crazy stuff) are not allowed, you can use this:
/\[php\](.*?)\[\/php\]/
The first matched group will be the text inside the tags. I think the regex is quite intuitive, except for the ?
: it will be lazy and match text only until the first closing tag, so that if you have [php]...[/php] [php]...[/php]
the regex will not match ...[/php] [php]...
(that is, between the first [php]
and the second [/php]
)
If you're using WordPress, but sure to look into the shortcode API.
http://codex.wordpress.org/Shortcode_API
And if not consider grabbing its code. It was written so it could be used in any app.
Try this:
$start_tag ='\\\\[php\\\\]\\\\s*';
$function ='((\\\\w+)\\\\s*\\\\(([^)]*)\\\\)';
$end_tag ='\\\\s*\\\\[\\\\/php\\\\]';
$re='/(' . $start_tag . $function . $end_tag . ')/';
which is:
( # 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
try using
\[php\](.*)\[\/php\]
You can search for string between these tags eg
\[PHP\](.+[^\b\[])\[/PHP\]
精彩评论