I am trying to match a semi dynamically generated string. So I can see if its the correct format, then extract the information from it that I need. My Problem is I no matter how hard I try to grasp regex can’t fathom it for the life of me. Even with the help of so called generators.
What I have is a couple different strings like the following. [@img:1234567890] and [@user:1234567890] and [@file:file_name-with.ext]. Strings like this pass through are intent on passing through a filter so they can be replaced with links, and or more readable names. But again try as I might I can’t come up with a regex for any given one of them.
I am looking for the format: [@word:] of which I will strip the [, ], @, and word from the string so I can then turn around an query my DB accordingly for whatever it is and work with it accordingly. Just the regex bit is holding me back.
Not sure what you mean by generators. I always use online matchers to see that my test cases work. @Virendra almost had it except forgot to escape the
[]charaters.You need to start and end with a regex delimeter, in this case the ‘/’ character.
Then we escape the ‘[]’ which is use by regex to match ranges of characters hence the ‘[‘.
Next we match a literal ‘@’ symbol.
Now we want to save this next match so we can use it later so we surround it with
().\wmatches aword. Basically any characters that aren’t spaces, punctuation, or line characters.Again match a literal
:.Maybe useful to have the second part in a match group as well so
(.*)will match any character any number of times, and save it for you.Then we escape the closing
]as we did earlier.Since it sounds like you want to use the matches later in a query we can use preg_match to save the matches to an array.
Would output
An especially helpful tool I’ve found is txt2re