如何获得括号内的所有值?

时间:2018-08-28 01:49:07

标签: php

我需要获取字符串内每个括号内的所有字符串/内容。 示例:$string = "hello (cool) how are you (i am okay) where are you from (i am from earth)";我正在像这样preg_match_all('#\((.*?)\)#', $nonumber, $match);使用preg_match_all,然后一旦我获得括号内内容的内容,我想将其放入数组

所以我希望括号内的每个内容都像这样放入数组。

第一个数组的值将为cool

第二个将具有我的值

我尝试回显$ match [0],但出现错误数组到字符串的转换。

简单地说,我希望值位于数组内。像这样 $ match [0]将具有cool的值 $ match [1]的值是我可以 等等

就像一个可以调用值的数组

我很绝望,不知道如何解决这个问题。请帮助

1 个答案:

答案 0 :(得分:0)

使用preg_match_all的方向正确,但是您应该使用模式\((.*?)\)

$regexp = "/\((.*?)\)/"; 
$string = "hello (cool) how are you (i am okay) where are you from (i am from earth)";
preg_match_all($regexp, $string, $matches); 
foreach ($matches[1] as $value) {
    echo $value . "\n";
}

cool
i am okay
i am from earth

Demo

相关问题