Fabrizio
Fabrizio

Reputation: 3776

regular expression php tags

I am usually pretty good to write simple regular expressions, but this time I cannot figure this out.

I need a regular expression that catches all the possible options:

<?php echo [^$]
<?php print [^$]
<? echo [^$]
<? print [^$]
<?echo [^$]
<?print [^$]
<?= [^$]
<?=[^$]

the [^$] stands for "non a $ character"

In other words I want to catch all the times that a print is done not using a variable.

I came up with something like this:

preg_match('/<\?[\s*|=|php]?\s*[echo\s|print\s]?\s*[^\$]/i',$content);

it doesn't work, can't figure out what would be the way to write it..

Upvotes: 0

Views: 982

Answers (3)

Todd Chaffee
Todd Chaffee

Reputation: 6824

This is because regular expressions in the short form are line noise. No one should have to try to program them, and especially no one should have to try to read them.

Try using the extended flag /x so you can use white space and add comments, both for others and for your future self.

This could be improved by someone better at regular expressions, but it gives you an example of how to start:

/
<\?                 # bracket and question mark
\s*                 # 0 to any white space
(php|echo|print|=)  # php or echo or print or equal sign
\s*                 # optional white space
(echo|print)*       # optional echo or print
\s*                 # optional white space
(\{|\[)             # curly brace or square bracket
\^                  # caret
\$                  # $
]                   # square bracket
/gx

Also, an online tool can help you build it up and see the results step by step:

http://gskinner.com/RegExr/

You can see a more detailed example of how to do this in php at the nettuts+ article on Advanced Regular Expressions Tips and Techniques.

Upvotes: 2

UberMouse
UberMouse

Reputation: 937

Not entirely sure what you want. but this /<\?(php|=)?\s*?(echo|print)?\s*?(\{|\[)\^\$\]/i regex matches against everything in the options (I think, I created it using a Java based regex tester and then modified it to work in PHP tester, the results seem to be useful though, but not sure what you want, it does return true).

Upvotes: 0

Joseph
Joseph

Reputation: 119847

<\?(((php)?\s*(echo|print))|=)\s*((\[|\{)\^\$])

where:

  • <\? - starts with <?

then followed by either:

  • (php)? - either has the php intro or not

  • (echo|print) - either echo or print

or:

  • = - a short hand echo

then followed by your [^$] or {^$]

Upvotes: 1

Related Questions