-2

I have string like bellow

Ref ID =={1234} [201] (text message)

I want to create an array like bellow

array(
    0 => 1234,
    1 => 201,
    2 => "text message"
)

Right now i am doing with Exploding the string method, but its took 8 lines of coding with multiple explode like bellow.

$data = array();
$str = 'Ref ID =={1234} [201] (text message)';
$bsArr1 = explode('}', $str);

$refIdArr = explode('{', $bsArr1);
$data[0] = $refIdArr[1];

$bsArr2 = explode(']', $bsArr[1]);
$codeArr = explode('[', $bsArr2[0]);
....
....
....

Is there anyway to achieve this with preg_match?

Karthikeyan Raju
  • 79
  • 1
  • 1
  • 6

2 Answers2

2

This will find one of [{( and capture all following lazy to }])

$str = "Ref ID =={1234} [201] (text message)";

preg_match_all("/[{|\[|\(](.*?)[\]|\)\}]/", $str, $matches);
var_dump($matches);

output:

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(6) "{1234}"
    [1]=>
    string(5) "[201]"
    [2]=>
    string(14) "(text message)"
  }
  [1]=>
  array(3) {
    [0]=>
    string(4) "1234"
    [1]=>
    string(3) "201"
    [2]=>
    string(12) "text message"
  }
}

https://3v4l.org/qKlSK

Andreas
  • 23,610
  • 6
  • 30
  • 62
0

Simple pregmatch:

preg_match('/{(\d+)}.*\[(\d+)].*\(([a-zA-Z ]+)\)/', 'Ref ID =={1234} [201] (text message)', $matches);

$arr[] = $matches[1];
$arr[] = $matches[2];
$arr[] = $matches[3];

echo '<pre>';
var_dump($arr);
die();
Edgar
  • 1,113
  • 3
  • 16
  • 30