使用 preg_match 查找所有 PHP 变量 [英] Find all PHP Variables with preg_match

查看:61
本文介绍了使用 preg_match 查找所有 PHP 变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 preg_match 查找所有 PHP 变量.我做了以下正则表达式:

How can I find all PHP variables with preg_match. I made the following regular expression:

$string = 'Hallo $var. blabla $var, $iam a var $varvarvar gfg djf jdfgjh fd $variable';
$instring = array();
preg_match_all('/\$(.*?)/', $string, $instring);
print_r($instring);

我只是不明白正则表达式是如何工作的.

I just don't understand how regular expressions work.

推荐答案

\$(.*?)

不是匹配 PHP 变量名的正确正则表达式.这种变量名的正则表达式实际上是PHP手册的一部分,并给出为(没有前导美元符号):

Is not the right regular expression to match a PHP variable name. Such a regular expression for a Variable Name is actually part of the PHP manual and given as (without the leading dollar-sign):

[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

所以在你的情况下,我会尝试:

So in your case I'd try with:

\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)

相反.看下面的例子:

<?php
/**
 * Find all PHP Variables with preg_match
 *
 * @link http://stackoverflow.com/a/19563063/367456
 */

$pattern = '/\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)/';

$subject = <<<'BUFFER'
Hallo $var. blabla $var, $iam a var $varvarvar gfg djf jdfgjh fd $variable
BUFFER;

$result = preg_match_all($pattern, $subject, $matches);

var_dump($result);
print_r($matches);

输出:

int(5)
Array
(
    [0] => Array
        (
            [0] => $var
            [1] => $var
            [2] => $iam
            [3] => $varvarvar
            [4] => $variable
        )

    [1] => Array
        (
            [0] => var
            [1] => var
            [2] => iam
            [3] => varvarvar
            [4] => variable
        )

)

如果您想了解 PHP 中的正则表达式是如何工作的,您需要阅读 PHP 手册以及所用正则表达式方言 (PCRE) 的手册.还有一本名为掌握正则表达式"的好书,我可以推荐阅读.

If you'd like to understand how regular expressions in PHP work, you need to read that in the PHP Manual and also in the manual of the regular expression dialect used (PCRE). Also there is a good book called "Mastering Regular Expressions" which I can suggest for reading.

另见:

这篇关于使用 preg_match 查找所有 PHP 变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆