简体   繁体   中英

How to match a regular expression that contains an arbitrary string, and get only that arbitrary string into a variable using PHP?

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?

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM