Aries
Aries

Reputation: 301

get string in between using Reqular Expression

I have a string in php as

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

How do i apply regular expression so i can extract the strings in between the @ char so that the resulting result will be an array say

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

@Fluffeh thanks for editing @ Utkanos - tried something like this

$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\"
        )

Upvotes: 0

Views: 76

Answers (2)

red-X
red-X

Reputation: 5128

You might go about it differently:

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

EDIT

Alright, give this a try than:

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

result:

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

Upvotes: 1

Shubham
Shubham

Reputation: 22307

Use a non-greedy match,

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

Upvotes: 3

Related Questions