Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't seem to get the regex pattern right

Tags:

regex

php

I need to check a string for a certain string, I want to use regex for this, but the more I keep trying, the more it confuses (and frustrates) me; I can't seem to get it right.

I need the expression to return true when the string contains something like this: [[module:instance]], but it needs to meet the following conditions:

  • Always open with 2 brackets [[
  • After the two brackets the string can contain everything except for :, and has no limit to it's length
  • After the string 1 : character must be present
  • After the : again a string that can contain everything except a :, and has no limit to it's length
  • Always close with 2 brackets ]]

Any help, tips, good tutorials, anything would be greatly appreciated!

Thanks in advance!

like image 410
Rick de Graaf Avatar asked Jan 20 '23 18:01

Rick de Graaf


1 Answers

Try this:

preg_match('/\[\[[^:]+?:[^:]+?]]/', $str, $match)

An explanation:

  • \[\[ matches the literal [[
  • [^:]+? matches anything but : (non-greedy)
  • : matches the literal :
  • [^:]+? matches anything but : (non-greedy)
  • ]] matches the literal ]].
like image 174
Gumbo Avatar answered Jan 30 '23 21:01

Gumbo