1

I'm really bad with regular expressions - never had enough time to learn it properly.

I'm trying to find all elements within the string which are wrapped with %% %% - example would be:

%%gallery%%

Any idea what regular expression would do the job here?

I'm going to later use it in PHP to replace the placeholders with relevant plugins.

user398341
  • 6,339
  • 17
  • 57
  • 75
  • `/%%(.+?)%%/s` would match that, for example. If you need more suitable/precise answers, you'd have to give more information on the problem. – dialer Mar 16 '11 at 14:31

4 Answers4

3
preg_replace("/%%\w+%%/", "replacement", "string");
adarshr
  • 61,315
  • 23
  • 138
  • 167
2

Something like /%%[a-z]+%%/i would work.

The [a-z]+ part tells there should be multiple characters (+) between a-z, surrounded with %'s. The /i makes it case insensitive.

TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
2

One regex would be:

%%(.*?)%%

As in:

$string = preg_replace('/%%(.*?)%%/', '{replacement for $1}', $string);

.* matches "anything" and ? makes it a non-greedy match, which means it tries to find as short a match as possible. If you have a string like "%%a%% %%b%%" you don't want it to find the longest match possible which would be a%% %%b.

%%a%% %%b%%         # Greedy
  ^^^^^^^

%%a%% %%b%%         # Non-greedy
  ^     ^

The $1 in the replacement string is whatever the matched tag is. In your example that'd be the word gallery.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

Look at: regex greedy problem (C#)

(?<!%)%%([^%]+)%%(?!%)

This matches exactly %%anything%%. It's non greedy an match also correctly content like 'Lorem ipsum %%sample%% lorem %%%ipsum%%% and so on'.

Community
  • 1
  • 1
dannyyy
  • 1,784
  • 2
  • 19
  • 43