Match and parse the content of a square-braced placeholder in text
Asked Answered
P

2

34

I have a PHP variable ($content) where I need to find a certain pattern that looks like this:

[gallery::name/of/the/folder/]

I would like to search:

- starting with literal characters `[gallery::`
- any other character (variable length)
- ending with "]"

So far, in PHP I have:

preg_match('/\[gallery\:/', $content, $matches, PREG_OFFSET_CAPTURE);

I can find [gallery: but that's it.

I would like to be able to find the rest (:name/of/the/folder/]).

Philosophical answered 13/4, 2012 at 14:25 Comment(0)
J
50

Try capturing it:

preg_match("/\[gallery::(.*?)]/", $content, $m);

Now $m is an array:

0 => [gallery::/name/of/the/folder/]
1 => /name/of/the/folder/
Junoesque answered 13/4, 2012 at 14:27 Comment(8)
If the string is 'starting with' something, make sure to prepend a '^' character to "\[gallery"Mussorgsky
wouldn't multiple occurences ([gallery::/name/of/the/folder/][gallery::/name/of/the/folder/]) cause problems with using a greedy capture on all characters?Goldschmidt
this will match [gallery::] i would change it to [gallery::(.+?)]Linkwork
I think OP meant that the pattern started with [gallery::, rather than the search string itself... Maybe... Not sure.Junoesque
@TimHoolihan it is a non-greedy captureLinkwork
@Linkwork Using a + is a valid answer too, but since it was supposed to be "any length" I figured 0 was included - after all, what if the path were the empty string (in other words, the current directory)?Junoesque
Thanks for the quick answer guys. It almost works but I'm having problems with the "/" in the folder name. If I type [gallery::/name/of/the/folder/] it doesn't find any results. But if I take out the "/" I find what I'm looking for. Anyway of finding with the "/" or do I need to replace it with another character?Philosophical
Are you sure you're typing the path in the right place? Might be a silly question, but there's no reason why a / in the search string would fail to match this regex.Junoesque
G
2

change your regex to

'/\[gallery::([A-Za-z\/]+)\]/'

Since I put the folder/path part in parenthesis, you should get a capture group out of it.

Goldschmidt answered 13/4, 2012 at 14:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.