我对正则表达式不太满意,所以我需要一些帮助。 我试图像这样在字符串中检索像函数一样的文本:
$str_var = " i do not need this datavar(i need this), i do not need this datavar(and also this), and so on";
preg_match('#\((.*?)\)#', $str_var, $match);
print_r($match)
我想:
arr value 1 = datavar(i need this)
arr value 2 = datavar(and also this)
到目前为止,我能够检索“这就是它”和“这就是它2”中的文本,但我需要检索函数名称和pharentesis的内容,如:“datavar(我需要这个) “和”datavar(还有这个)“
任何想法
答案 0 :(得分:3)
如果您在问题的评论中确认,如果括号前的单词仅由字母组成,那么这可能就是您要找的内容:
<?php
$subject = " i do not need this ineedthis(and also this), i do not need this ineedthistoo(and also this 2), and so on";
preg_match_all('#(\w+\([^)]+\))#', $subject, $matches);
print_r($matches);
上述代码的输出为:
Array
(
[0] => Array
(
[0] => ineedthis(and also this)
[1] => ineedthistoo(and also this 2)
)
[1] => Array
(
[0] => ineedthis(and also this)
[1] => ineedthistoo(and also this 2)
)
)
更新:
如果括号前的单词是固定的文字字符串datavar
,那么您可以将上面的代码简化为:
<?php
$subject = " i do not need this ineedthis(and also this), i do not need this ineedthistoo(and also this 2), and so on";
preg_match_all('#(datavar\([^)]+\))#', $subject, $matches);
print_r($matches);
答案 1 :(得分:1)
根据具体情况,您可以使用以下内容:
(\w+\([^)]+\))
或在php中:
preg_match('(\w+\([^)]+\))', $str_var, $match);
这意味着一系列单词字符\w+
后跟一个(
,一些字符不是)
,最后是结束)
。
查看示例here。