How to look for a number from 1 to 4 chars long

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
m2244
Forum Newbie
Posts: 2
Joined: Tue Mar 20, 2012 9:14 am

How to look for a number from 1 to 4 chars long

Post by m2244 »

Hello,

I am trying to set a variable to a number from a string. The number can be 1 to 4 characters long. Right now I have it returning the index for the start of the number, I need it to return the number itself.

In the example below I want to captrue the '581'. This is in AS3 by the way.

Any suggestions?

Code: Select all

width="581"
User avatar
tr0gd0rr
Forum Contributor
Posts: 305
Joined: Thu May 11, 2006 8:58 pm
Location: Utah, USA

Re: How to look for a number from 1 to 4 chars long

Post by tr0gd0rr »

If the string is html, it would be best to parse it with DOMDocument. Otherwise you can use preg_match.
User avatar
ragax
Forum Commoner
Posts: 85
Joined: Thu Dec 15, 2011 1:40 pm
Location: Nelson, NZ

Re: How to look for a number from 1 to 4 chars long

Post by ragax »

A regex option:

Code: Select all

$string = 'width="581"';
$regex = '~(?i)width="(\d{1,4})~';
$hit = preg_match($regex,$string,$match);
if($hit) echo $match[1].'<br />';
Now go read up on regex to understand why that works.
:D
Post Reply