ihateartists
ihateartists

Reputation: 328

preg_match regex to include dashes in words?

 $name = 'Canon OEM BC-30e BK';
 preg_match("/OEM (\\w+)/", $name, $matches);
 $hash = $matches[1];

How can I get $hash to return 'BC-30e' in this example? Right now it is returning 'BC-'. I'm a bit new to learning regular expressions and am struggling to get the result intended. I've been over on http://regexr.com/ trying to hammer it out for a minute and am finding this result difficult. =(

To my understanding the 'w' is making it a word, which is excluding dashes. However when I change it to something like below I simply get 'B.'

 $name = 'Canon OEM BC-30e BK';
 preg_match("/OEM ([A-Za-z-])/", $name, $matches);
 $hash = $matches[1];

Can someone shed some light on what I'm doing wrong here? I would be most appreciative =)

Upvotes: 0

Views: 236

Answers (2)

Thomas B Preusser
Thomas B Preusser

Reputation: 1189

You just need to match multiple characters and add digits in your last regex:

preg_match("/OEM ([A-Za-z0-9-]+)/", $name, $matches);

Upvotes: 1

splash58
splash58

Reputation: 26143

You can find non-space characters:

/OEM ([\\S]+)/

Upvotes: 2

Related Questions