trapach
trapach

Reputation: 41

Python regex to PHP?

I'm trying to convert a Python script into PHP.

The following 2 regular expressions work in Python:

'/\*\*([\w\n\(\)\[\]\.\*\'\"\-#|,@{}_<>=:/ ]+?)\*/'
'(?:\* ([\w\d\(\),\.\'\"\-\:#|/ ]+)|(?<= @)(\w+)(?: (.+))?)'

...however, if I try to run them in PHP I get:

Warning: preg_match_all() [function.preg-match-all]: Unknown modifier ']'

How come?

Upvotes: 3

Views: 1484

Answers (2)

Tim Pietzcker
Tim Pietzcker

Reputation: 336178

The reason is that PHP expects delimiters around its regexes, so it treats the first and second slash as delimiters and tries to parse what follows as modifiers.

Surround your regex with new delimiters and try again (I also removed some unnecessary backslashes):

'%/\*\*([\w\n()\[\].*\'"#|,@{}_<>=:/ -]+?)\*/%'
'%(?:\* ([\w\d(),.\'"\:#|/ -]+)|(?<= @)(\w+)(?: (.+))?)%'

Hint: Use RegexBuddy to do these things. It will take a regex written in language A and convert it to language B for you.

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

PCRE (including preg_match_all) requires a pattern boundary. You need to wrap the entire pattern in /, @, #, %, or many other possible options. I suggest % as it doesn't look like you are using it in either pattern, that is:

%(?:\* ([\w\d\(\),\.\'\"\-\:#|/ ]+)|(?<= @)(\w+)(?: (.+))?)%

Upvotes: 1

Related Questions