简体   繁体   English

如何匹配包含任意字符串的正则表达式,并使用PHP仅将该任意字符串转换为变量?

[英]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. 我试图用PHP编写一种非常简单的标记语言,其中包含[x = 123]之类的标记,并且我需要能够匹配该标记并仅提取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. 您可以使用preg_match在字符串中搜索正则表达式。

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). 在此处查看文档: http : //www.php.net/manual/en/function.preg-match.php ,以获取有关如何使用它的更多信息(以及一些示例)。 You might also want to take a look at preg_grep . 您可能还想看看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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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