0

I am writing some snippet script with PHP,

I have these kind of string variable

 $msg="Dear [[5]]
    We wish to continue the lesson with the [[6]]";

i need to grab 5 and 6 from this $msg and assign to an array ex array(5,6)

because those are the snippets numbers, any one know how to do that using PHP

thank you for help

1
  • Foreseeing your next step, it might be easier to use preg_replace_callback to find and substitute these markers in one step. Commented Sep 18, 2012 at 9:31

2 Answers 2

4

Use preg_match_all:

$msg = "Dear [[5]] We wish to continue the lesson with the [[6]]";
preg_match_all("/\[\[(\d+)\]\]/", $msg, $matches);

If there is a match, $matches[1] will then contain an array with the matched numbers:

Array
(
    [0] => 5
    [1] => 6
)

DEMO.

Sign up to request clarification or add additional context in comments.

4 Comments

I applied this to my script my string was "test closingdear [[12]]" and it gaves me this kind of array in var dump array(2) { [0]=> array(1) { [0]=> string(6) "[[12]]" } [1]=> array(1) { [0]=> string(2) "12" } } there is extra items, any idea what is going here :)
@SunethKalhara: Can you give me the exact line you executed? You need to consider only the first position of the resulting array.
$rulz="test closingdear [[12]]"; preg_match_all("/[[(\d+)]]/", $rulz, $matches); var_dump($matches);
@SunethKalhara: You didn't escape the [ and ] like in my example. They are special regex characters. Also, you need to consider only $matches[1]. Check this demo ideone.com/IbHhI.
1

Here is what you want:

<?php

$msg = "Dear [[5]]
 We wish to continue the lesson with the [[6]]";

preg_match_all('/\[\[([0-9+])\]\]/', $msg, $array);

$array = $array[1];

print_r($array);

?>

Output:

Array
(
    [0] => 5
    [1] => 6
)

4 Comments

I don't really see how's this any different from my answer.
I was typing this when there was no answer :)
$array = $array[0]; is worked for me, do you know why is that :)
Because preg_match places all found in index[0] which isn't what you want and from that each () of pattern will be stored in other indexes starting from 1. In this case in our pattern, we have only 1 parentheses so the index[1] would be where the found data will be stored ...

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.