2

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!

2
  • Shouldn't your IDE be able to format your code for you? Commented Jun 26, 2011 at 15:57
  • I have tried several IDEs and they don't format files with mixed html and php that well. If you know of one that does I would be happy to start using it. Commented Jun 26, 2011 at 19:39

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

For the curious, the *? makes the regular expression lazy, so it will stop at the first closing ?> tag instead of the last one.
0
var php_tag_pattern = /<\?=?.+?\?>/;

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.