开发者

JavaScript Regular Expression to find PHP tags

I have googled for a regex to grab and also read a few tutorials and I can't seem to get a solid regular expression to do this.

What I need to do is write a JavaScript regular expression that will match PHP tags within a string.

I have inherited a large php project where the views that have mixed html and php are not very readable. So what I'm doing is writing an IDE extension for my own personal use to strip out php that is mixed in a php view in order to run an HTML indentation script on it without confusing the HTML indentation script. Then after the indentation script has finished I go back and re-insert the php again.

What I have so far is this (I converted this from a regex that looks for brackets [], I knew it wouldn't match everything but it got me far enough to flesh out my IDE extension):

var php_tag_pattern = /<\?[^<>]*\?>/;

Now for obvious reasons it is not matching on code like this:

<?=$common->format_number($acct_info['number'])?>

or this:

<?
$wifi = $wifi_lib->wifi_radius($v['radiusgroupname']);
if (!empty($wifi)) :?>

I have been messing around with this for the last several hours so I thought I would finally ask for help 开发者_如何转开发to see what I'm missing.

Thanks!


To match multi-line php text you will need an implementation of DOTALL in Javascript. Unfortunately Javascript doesn't have s flag but there is a workaround. Try this code:

var php_tag_pattern = /<\?[=|php]?[\s\S]*?\?>/;

[\s\S] will make sure to match php text in multi line including new lines as well.


var php_tag_pattern = /<\?=?.+?\?>/;


var regex = /<\?[=|php]?[^<>]*\?>/;

You will also need to use the multiline modifier new RegExp(regex, "gim"). The 'g' is global, 'i' is case insensitive and 'm' multiline.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜