0

I'm trying to write a very simple markup language in PHP that contains tags like [x=123], and I need to be able to match that tag and extract only the value of x.

I'm assuming the answer involves regex but maybe I'm wrong.

So if we had a string:

$str = "F9F[x=]]^$^$[x=123]#3j3E]]#J";

And a regular expression to match:

/^\[x=.+\]$/

How would we get only the ".+" portion of the matching string into a variable?

ch7527
  • 203
  • 1
  • 6
  • It's called capture groups. Your regex incorrectly looks for `^` start and `$` end, and the `.+` is too greedy. * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Oct 30 '12 at 04:05

2 Answers2

0

You can use preg_match to search a string for a regular expression.

Check out the documentation here: http://www.php.net/manual/en/function.preg-match.php for more information on how to use it (as well as some examples). You might also want to take a look at preg_grep.

jflores
  • 483
  • 6
  • 18
0

Following code should work for you:

$str = "F9F[x=]]^$^$[x=123]#3j3E]]#J";
if (preg_match('~\[x=(?<valX>\d+)\]~', $str, $match))
   echo $match['valX'] . "\n";

OUTPUT:

123
anubhava
  • 761,203
  • 64
  • 569
  • 643