获取所有看起来像PHP变量名的子字符串

问题描述 投票:0回答:1

假设我有一根绳子

My name is $name and my pet is $animal

如何检查字符串中是否有变量?如果有,将它们添加到一个数组中,如“

$array = ['$name', '$animal'];

会是一些

pregmatch()
吗? ...但随后需要提取所有
$+sometextafterthesymbol
并在其后保留一个空格“$°”。 有什么想法吗?

php string variables text-extraction
1个回答
1
投票

您可以为此使用正则表达式。 以下内容将匹配任何美元符号后跟 1 个或多个单词字符(字母、数字或下划线):

preg_match_all('/\$(\w+)/', $string, $matches);

$matches

Array
(
    [0] => Array
        (
            [0] => $name
            [1] => $animal
        )

    [1] => Array
        (
            [0] => name
            [1] => animal
        )

)

请记住,

$string
,如果硬编码,必须用单引号括起来 (
'
)。

© www.soinside.com 2019 - 2024. All rights reserved.