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,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125

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
  • 3,948
  • 1
  • 18
  • 16