0

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

2 Answers 2

3

Use a non-greedy match,

preg_match_all("/@(.*?)@/", $str, $matches);
var_dump($matches); 
Sign up to request clarification or add additional context in comments.

6 Comments

Would this not catch the , as a match?
No, it will not catch the comma. Only text between each @. Here's an example without laziness: preg_match_all ('#@([^@]+)#', $str, $matches);
Oh sorry for the wrong update, I myself got confused with red-X comment.
because im trying the regex from this site, but i cant seem to have my expected result
What result you expect? I am getting the exact strings you need.
|
1

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
)

2 Comments

And what if there are commas in the expressions to be captured? Better to explode on '@' and then filter out the commas, I think.
@dnagirl that wasnt a requirement in the question but in that case see edit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.