1

I have these multiple strings like the 3 below

 - Framing 50mm x 100mmx3.0m
 - Loglap 22x100x4.5
 - Decking 32 x 150 @3.0

What i want to do is extract the numbers into an array.

The numbers for each are either separated by @ or x So for Framing the first array value is 50, second is 100, third is 3.0

I was thinking of using explode but the strings format aren't consistent.

How do i solve?

2
  • do the characters x or @ denote anything specific, or is the only thing you're interested in the actual numbers themselves? Commented Sep 23, 2015 at 14:15
  • I'm only interested in the numbers, the x and @ are just separators. Commented Sep 23, 2015 at 14:17

2 Answers 2

2

You can simply use preg_match_all like as

$str = "Framing 50mm x 100mmx3.0m";

preg_match_all('/([\d.]+)/',$str,$m);
print_r($m[0]);

Output:

Array
(
    [0] => 50
    [1] => 100
    [2] => 3.0
)

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

This is the one, the cleanest!
1

You can use

$string = "50mm x 100mmx3.0m";
$formated = preg_replace("/[^0-9,.]/", ",", $string);

To replace all non-numeric values from a string and replace it with commas so it can be easier to convert to array, but the problem will be that the string that you want might be full of commas after commas.

The above code will result in: 50,,,,,100,,,3.0,

So, the solution COULD be, replace double commas with an empty value.

$formated = str_replace(",,", "", $formated);

Now you have: 50,100,3.0,

Exploding it will result in an array of numbers:

$array = explode(",", $formated);

Now you have ["50", "100", "3.0"]

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.