假设我有一根绳子
My name is $name and my pet is $animal
。
如何检查字符串中是否有变量?如果有,将它们添加到一个数组中,如“
$array = ['$name', '$animal'];
会是一些
pregmatch()
吗? ...但随后需要提取所有 $+sometextafterthesymbol
并在其后保留一个空格“$°”。
有什么想法吗?
您可以为此使用正则表达式。 以下内容将匹配任何美元符号后跟 1 个或多个单词字符(字母、数字或下划线):
preg_match_all('/\$(\w+)/', $string, $matches);
$matches
:
Array
(
[0] => Array
(
[0] => $name
[1] => $animal
)
[1] => Array
(
[0] => name
[1] => animal
)
)
请记住,
$string
,如果硬编码,必须用单引号括起来 ('
)。