[英]PHP using regular expressions to extract content from a 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);
如果我們不知道數字的長度然后讓空格是數字之后的下一個字符,那么:
$string = 'YOURSTRING';
$offset = strpos($string, 'Out Stk #') + 11;
$end = strpos($string, ' ', $offset);
$final = substr($string, $offset, $end-$offset);
你可以使用:
if (preg_match( '/Our Stk #: ([0-9\\-]+)/', $str, $match ))
echo $match[1];
你可以這樣做:
<?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];
}
僅當您要查找的數字部分始終為digits-digits
形式時digits-digits
。 @ Richard86給出了一個更通用的解決方案,包含任意數量和任意數量的破折號,作為您問題的另一個答案。
編輯:
為了避免破折號周圍沒有數字的情況,正如@ 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.