简体   繁体   中英

PHP Regular Expression: Get numbers between underscore

I have an issue with a regular expression which just doesn't seem to work out the way I want.

Here are two examples of (different) input strings:

  • 1111_market1233_ 700x100 _BLU
  • 1111_market232_ 8000x000 _AES
  • 1111_market11_ 689x41777 _CER

Of course, not having the best knowledge of regular expressions, I fail to get the bold parts of the text for different reasons. Below is my example of doing it:

preg_match("/_([^0-9])x([^0-9])_/", $input_line, $output_array);

Of course, this is not working. The expected output I want is:

  • 700x100
  • 8000x000
  • 689x41777

You almost got it. Just add repetition and remove ^ :

/_([0-9]+)x([0-9]+)_/

^ within a character set makes the set match anything but what is inside. Aka [^0-9] would match anything that is not a digit.

Also character sets by themselves match only one character. Aka [0-9] matches just one digit. + means match 1 or more times .


If you want to remove the underscores from the match, you would use positive lookahead and lookbehind . It will make the regex just verify they are there, instead of including them in the match:

 /(?<=_)([0-9]+)x([0-9]+)(?=_)/ 

See it in action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM