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开发者_JAVA技巧 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
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)) {
You could use:
if (preg_match( '/Our Stk #: ([0-9\\-]+)/', $str, $match ))
echo $match[1];
$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);
<?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];
?>
精彩评论