使用正则表达式获取字符串

时间:2012-08-13 11:15:02

标签: php regex

我在php中有一个字符串

$str = "@113_Miscellaneous_0 = 0@,@104_documentFunction_0 = 1@";

如何应用正则表达式,以便我可以在@cchar之间提取字符串 这样结果将是一个数组说

result[0] = "113_Miscellaneous_0 = 0";  
result[1] = "104_Miscellaneous_0 = 1";  

@Fluffeh感谢您的编辑 @ Utkanos - 试过这样的事情

$ptn = "@(.*)@";  
preg_match($ptn, $str, $matches);  
print_r($matches);  

output:
     Array
        (
            [0] => \"113_Miscellaneous_0 = 0\",\"104_documentFunction_0 = 1\"
            [1] => \"113_Miscellaneous_0 = 0\",\"104_documentFunction_0 = 1\"
        )

2 个答案:

答案 0 :(得分:3)

使用非贪婪的比赛,

preg_match_all("/@(.*?)@/", $str, $matches);
var_dump($matches); 

答案 1 :(得分:1)

你可能会采用不同的方式:

$str = str_replace("@", "", $str);
$result = explode(",", $str);

修改

好吧,试一试:

$ptn = "/@(,@)?/";
$str = "@113_Miscellaneous_0 = 0@,@104_documentFunction_0 = 1@";
preg_split($ptn, $str, -1, PREG_SPLIT_NO_EMPTY);

结果:

Array
(
    [0] => 113_Miscellaneous_0 = 0
    [1] => 104_documentFunction_0 = 1
)