I Am Stack
I Am Stack

Reputation: 241

Get a word using php regular expression from string

This is my strings

905 Lumens/7.2W/3000K/82CRI/L85 50Khrs
1224 Lumens - 9.6W - 3000K
1632 3000K 12.8W 50Khrs
2448 Lumens/3000K/19.2W 150Khrs

Now I want to get only the word that have number with W Like: 7.2W, 9.6W

I want to get this in a variable using regular expression.

My code is: $watt = preg_match("/[\d]+W/", $string);

currently my code return with array, but I want only string with 7.2W or 9.6W or similar ..

Please help.

Upvotes: 0

Views: 36

Answers (1)

u_mulder
u_mulder

Reputation: 54796

First of all - founded matches are gathered in a third argument $matches.

Second - you need to consider a dot(.) in your regexp:

preg_match("/(\d+\.\d+W)/", $string, $matches);
print_r($matches);
echo $matches[0];   // full match found

If . is optional - then:

preg_match("/(\d+(\.{0,1})\d+W)/", $string, $matches);
print_r($matches);
echo $matches[0];   // full match found

Upvotes: 1

Related Questions