简体   繁体   English

PHP使用正则表达式从字符串中提取内容

[英]PHP using regular expressions to extract content from a string

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? 我有以下字符串,我想从中提取“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
$string = 'YOURSTRING';
$offset = strpos($string, 'Out Stk #') + 11;
$final = substr($string, $offset, 8);

if we do not know the length of the number then and lets say whitespace is next character after the number, then: 如果我们不知道数字的长度然后让空格是数字之后的下一个字符,那么:

$string = 'YOURSTRING';
$offset = strpos($string, 'Out Stk #') + 11;
$end = strpos($string, ' ', $offset);
$final = substr($string, $offset, $end-$offset);

You could use: 你可以使用:

if (preg_match( '/Our Stk #: ([0-9\\-]+)/', $str, $match ))
    echo $match[1];

You could do: 你可以这样做:

<?php

$str = "Microchip Technology Inc.
18 PIN, 7 KB FLASH, 256 RAM, 16 I/O 

Mfr's Part #: PIC16F648A-I/SO 
Our Stk #: 383-0408";

if (preg_match('/Our Stk #: (\d*-\d*)/', $str, $matches)) {
    echo $matches[1];
}

this works only if the number part you're looking for has always the form digits-digits . 仅当您要查找的数字部分始终为digits-digits形式时digits-digits A more general solution, with any number and any amount of dashes is given by @Richard86 as another answer to your question. @ Richard86给出了一个更通用的解决方案,包含任意数量和任意数量的破折号,作为您问题的另一个答案。

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: 为了避免破折号周围没有数字的情况,正如@ Richard86在评论中所说,常规表达应该如下所示:

if (preg_match('/Our Stk #: (\d+-\d+)/', $str, $matches)) {
<?php

$text = "Microchip Technology Inc.
18 PIN, 7 KB FLASH, 256 RAM, 16 I/O 

Mfr's Part #: PIC16F648A-I/SO 
Our Stk #: 383-0408";

preg_match('/Our Stk #: (.*)/', $text, $result);
$stk = $result[1];

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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