如何在PHP中的字符串中的特定单词之后获取最近的下一个12个字母长的单词

时间:2019-09-20 07:18:44

标签: php

我在下面有字符串 $ string ='收件人:发票编号开票日期704319003027 15-06-2019 PAPIYA DUTTA销售订单编号销售订单日期PAIKPARA,MURARAI ROAD区:BIRBHUM,NALHATI-731220';

我想要在“发票编号”一词后加12个字符长的“ 704319003027”

$string = 'Invoice Number: Invoice Name: 704319003027 Rahul Sinha 
 Account Information: Some text here';

 $invoice_no = substr($string, strpos($string, 'Invoice Number:') + strlen($matches[0]), 12);
echo $invoice_no;

4 个答案:

答案 0 :(得分:1)

您可以使用preg的后向获取Invoice NumberDemo之后的第12个字符的第一个数字

if(preg_match("/(?<=Invoice Number).*([0-9]{12})/",$string,$matches)){
    echo var_dump($matches[1]);
}

答案 1 :(得分:0)

选项1

<?php
$data = "Invoice Number: 704319003027 Invoice Name: 704319003027 Rahul Sinha Account Information: Some text here";

$whatIWant = substr($data, strpos($data, "Number: ") + 8);
$whatIWant2 = substr($whatIWant, 0, 12);

echo $whatIWant2;

选项2

<?php
$data = "Invoice Number: Invoice Name: 704319003027 Rahul Sinha Account Information: Some text here";

$data = explode(' ', $data);

foreach($data as $key => $value) {
   if (intval($value) && strlen($value) == 12) {
     $data = $value;
     break;
   }
}

var_dump($data);

答案 2 :(得分:0)

您可以使用preg_match提取“发票名称”后面的数字:

preg_match('/Invoice Name: ([\d]+) /', $string, $matches);
echo $matches[1];

答案 3 :(得分:0)

使用正则表达式匹配字符串中所需的文本,如下所示:

$string = 'Invoice Number: Invoice Name: 704319003027 Rahul Sinha Account Information: Some text here';
preg_match('@Invoice Name: (\d{12})@',$string,$matches);
if( !empty( $matches ) )echo $matches[1];