1

I know I can do this like following way, but is there a one line method like using regex to get everything before the comma as $first and everything after comma as $second?

$data = "m-12,s-52";
$arr = explode(",", $data);
$first = $arr[0];
$second = $arr[1];
halfer
  • 19,471
  • 17
  • 87
  • 173
Behseini
  • 5,746
  • 20
  • 67
  • 114

1 Answers1

0

You can get the $first and $second using this one line regex code

$data = "m-12,s-52,s-52";
$beforefirstcomma = preg_replace("/,(.+)/", "", $data);
$afterlastcomma = preg_replace("/(.+),/", "", $data);
$afterfirstcomma = preg_replace("/^[^,]+,+/", "", $data);

// outputs
echo $beforefirstcomma; // m-12
echo "<br>";
echo $afterlastcomma; // s-52
echo "<br>";
echo $afterfirstcomma; // s-52,s-52

Final Note
I still recommend using explode() because it is more efficient and performant than running preg_replace() multiple times on the $data string.

Tunji Oyeniran
  • 2,760
  • 1
  • 17
  • 15