ballhogjoni Posted October 18, 2013 Share Posted October 18, 2013 I'm trying to match SKU: DD-969991 and get DD-969991 out of matches. if (preg_match('/SKU:\s(\w+)/', $content, $matches)) { $sku = $matches[1]; } with this I get DD. I need the whole string DD-969991 Quote Link to comment https://forums.phpfreaks.com/topic/283086-cant-figure-this-out/ Share on other sites More sharing options...
.josh Posted October 18, 2013 Share Posted October 18, 2013 \w is shorthand for a "word" character class, and is the equivalent of [a-z0-9_] which matches letters, numbers or underscore. It stops at "DD" because a hyphen isn't a "word" character. A liberal approach would be to do this: /SKU:\s(\S+)/ This will capture anything that is not a space. A more restrictive approach could be this: /SKU:\s(\w+-\w+)/ This will match one or more "word" characters followed by a hyphen followed by one or more "word" characters. An even more restrictive approach could be this: /SKU:\s(\w+-\d+)/ This will match one or more "word" characters followed by a hyphen followed by one or more numbers. An even more restrictive approach could be this: /SKU:\s([A-Z]{2}-\d{6})/ This matches for 2 uppercase letters followed by a hyphen followed by 6 numbers Quote Link to comment https://forums.phpfreaks.com/topic/283086-cant-figure-this-out/#findComment-1454470 Share on other sites More sharing options...
ballhogjoni Posted October 18, 2013 Author Share Posted October 18, 2013 (edited) Thanks for the feedback. Is there a way to find DD-239dsk-2348 and D-4ida-8aa-3ja? Basically the hyphens can be anywhere in the string. They aren't always in the same location. And there can be more than one. Edited October 18, 2013 by ballhogjoni Quote Link to comment https://forums.phpfreaks.com/topic/283086-cant-figure-this-out/#findComment-1454474 Share on other sites More sharing options...
Solution .josh Posted October 18, 2013 Solution Share Posted October 18, 2013 Okay, then you can use the first pattern I showed: /SKU:\s(\S+)/ As I said, this will capture anything that is not a space. A more restrictive version based on your feedback could be: /SKU:\s([\w-]+)/ This will capture one or more "word" characters or hyphens But "word" characters include underscore, so even more restrictive would be: /SKU:\s([a-z0-9-]+)/i This will explicitly only match letters, numbers and hyphens. Notice I added the "i" on the end of there, after the closing delimiter. This is to make the match case-insensitive Quote Link to comment https://forums.phpfreaks.com/topic/283086-cant-figure-this-out/#findComment-1454475 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.