user311509
user311509

Reputation: 2866

Grab Number using Preg_Match

$str = 'title="room 5 stars"';
preg_match_all('/title="([0-9]+)"/sm', $str, $rate);

I need to grab number 5 from title. The regex doesn't work!

If i do this:

preg_match_all('/title="([0-9]+)"/sm', $str, $rate);

I get:

room 5 stars

However, this one doesn't return anything:

'/title="([0-9]+)"/sm'

Where did i go wrong?

Upvotes: 1

Views: 101

Answers (3)

Vishal
Vishal

Reputation: 2060

* is a greedy match, it might give wrong results sometimes.

You can use /title=".*?(\d+).*?"/ which is a lazy match and will search the least characters.

You can also try this free tool for regex matching: RegExr

Upvotes: 0

soju
soju

Reputation: 25312

You forgot to match the text before and after your number. Try with : /title=".*([0-9]+).*"/

PS: you don't need m and s option

Upvotes: 1

ohaal
ohaal

Reputation: 5268

You're not taking into account the words around the number, try this:

$str = 'title="room 5 stars"';
preg_match_all('/title=".*(\d+).*"/', $str, $rate);

// The number is then in $rate[1][0];

Upvotes: 3

Related Questions