0

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.

2
  • }* matches the brace zero or more times... you might want to try something like }.*{ Commented Oct 5, 2009 at 13:03
  • tried that, and it returns {theme}pink{/theme}, I need to get the value pink now Commented Oct 5, 2009 at 13:05

5 Answers 5

3

* 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);
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2
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.

Comments

0
$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.

Comments

0
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.