0

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 Answers 2

4

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.
Sign up to request clarification or add additional context in comments.

3 Comments

@Barmar Awesome dude. Can you explain the regex in your answer ? explain each one of them if its possible for you
@Mohammad I've added it, but it hardly seemed necessary to go into detail for such a basic regexp. It doesn't use anything advanced, so even a regexp beginner should understand it. You should go to www.regular-expression.info and read the tutorial.
@Barmar Thanks, I will check it out.
0

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

Hope it will work for you :)

Comments

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.