简体   繁体   中英

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?

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 . 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:

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];

?>

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