how to split a string into array using preg_split with two condition

644 views Asked by At

I have a string like this : x320h220

I want to split this string into two variables : $width and $height

I Can split it using explode but I have to use this method twice to get these values so I found out preg_split will do the trick. But I don't know the Regex to split these string into two variables (find if string contain x then cut the rest till h and then cut the rest again in another variable) which they should be like :

$width = 320;
$height = 220;

any suggestion ?

2

There are 2 answers

3
Barmar On BEST ANSWER

Use preg_match(), not preg_split(). Use capture groups to extract the two numbers.

if (preg_match('/x(\d+)h(\d+)/', $string, $match) ) {
    $width = $match[1];
    $height = $match[2];
}

In the regexp:

  • x and h match themselves literally
  • \d+ matches a sequence of digits
  • Putting () around the digit sequence creates a capture group, so the matched portions are put into the $match array.
0
Amit Sahu On

use this $size = preg_split("/[xh]/", "x320h220", -1, PREG_SPLIT_NO_EMPTY)

Hope it will work for you :)