PHP使用正则表达式从字符串中提取内容
我有以下字符串,我想从中提取“383-0408”,显然内容发生了变化,但零件号始终遵循字符串“Our Stk #:”,如何才能最优雅地从字符串中提取此信息?
Microchip Technology Inc.
18 PIN, 7 KB FLASH, 256 RAM, 16 I/O
Mfr's Part #: PIC16F648A-I/SO
Our Stk #: 383-0408
I have the following String and I want to extract the "383-0408" from it, obviously the content changes but the part number always follows the String "Our Stk #:", how can I most elegantly extract this information from the string?
Microchip Technology Inc.
18 PIN, 7 KB FLASH, 256 RAM, 16 I/O
Mfr's Part #: PIC16F648A-I/SO
Our Stk #: 383-0408
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以这样做:
仅当您要查找的数字部分始终采用
digits-digits
形式时,此方法才有效。 @Richard86 给出了一个更通用的解决方案,可以使用任意数量和任意数量的破折号,作为您问题的另一个答案。编辑:
为了避免破折号周围没有数字的情况,正如@Richard86在评论中所说,正则表达式应该如下所示:
You could do:
this works only if the number part you're looking for has always the form
digits-digits
. A more general solution, with any number and any amount of dashes is given by @Richard86 as another answer to your question.Edit:
In order to avoid the case when no digits are around the dash, as @Richard86 said in a comment, the regular expresion should look like:
你可以使用:
You could use:
如果我们不知道数字的长度,并且假设空白是数字后面的下一个字符,那么:
if we do not know the length of the number then and lets say whitespace is next character after the number, then: