Elitmiar
Elitmiar

Reputation: 36839

Getting a random string within a string

I need to find a random string within a string.

My string looks as follows

{theme}pink{/theme} or {theme}red{/theme}

I need to get the text between the tags, the text may differ after each refresh.

My code looks as follows

$str = '{theme}pink{/theme}'; 
preg_match('/{theme}*{\/theme}/',$str,$matches);

But no luck with this.

Upvotes: 0

Views: 131

Answers (5)

patcoll
patcoll

Reputation: 976

$matches = array();
$str = '{theme}pink{/theme}';
preg_match('/{([^}]+)}([^{]+){\/([^}]+)}/', $str, $matches);

var_dump($matches);

That will dump out all matches of all "tags" you may be looking for. Try it out and look at $matches and you'll see what I mean. I'm assuming you're trying to build your own rudimentary template language so this code snippet may be useful to you. If you are, I may suggest looking at something like Smarty.

In any case, you need parentheses to capture values in regular expressions. There are three captured values above:

([^}]+)

will capture the value of the opening "tag," which is theme. The [^}]+ means "one or more of any character BUT the } character, which makes this non-greedy by default.

([^{]+)

Will capture the value between the tags. In this case we want to match all characters BUT the { character.

([^}]+)

Will capture the value of the closing tag.

Upvotes: 0

Ignas R
Ignas R

Reputation: 3409

preg_match_all('/{theme}(.*?){\/theme}/', $str, $matches);

You should use ungreedy matching here. $matches[1] will contain the contents of all matched tags as an array.

Upvotes: 2

PhiLho
PhiLho

Reputation: 41142

'/{theme}(.*?){\/theme}/' or even more restrictive '/{theme}(\w*){\/theme}/' should do the job

Upvotes: 2

VolkerK
VolkerK

Reputation: 96159

* is only the quantifier, you need to specify what the quantifier is for. You've applied it to }, meaning there can be 0 or more '}' characters. You probably want "any character", represented by a dot.
And maybe you want to capture only the part between the {..} tags with (.*)

$str = '{theme}pink{/theme}'; 
preg_match('/{theme}(.*){\/theme}/',$str,$matches);
var_dump($matches);

Upvotes: 3

knittl
knittl

Reputation: 265211

preg_match('/{theme}([^{]*){\/theme}/',$str,$matches);

[^{] matches any character except the opening brace to make the regex non-greedy, which is important, if you have more than one tag per string/line

Upvotes: 0

Related Questions