繁体   English   中英

获取PHP字符串中某些单词之前的最后一个数字

[英]Get last numeric before certain word in PHP String

我的php字符串包含pcsPcsPCS

如何获取单词pscPcsPCS之前的最后一个数字?

例:

//string:
$fStr = '51672 : Cup 12 Pcs';
$sStr = '651267 : Spoon 128 pcs @xtra';
$tStr = '2 Pcs';

//expected result:
fStr = 12
sStr = 128
tStr = 2

是否可以使用正则表达式?

任何帮助将不胜感激。 谢谢

更新:

上述情况已通过以下答案解决。 但是,如果字符串中有多个单词pcs我该如何处理。 例如

//string
$multiStr = '178139 : 4 Pcs pen and 2 Pcs book';

//expected result
Array
(
   [0] => 4
   [1] => 2
)
preg_match('/(\d+)\ ?pcs/i', $string, $match);
$output = $match[1];

这是一个测试

您可以使用preg_match()生成具有前瞻性的全字符串匹配:

$sStr = '651267 : Spoon 128 pcs @xtra';
echo preg_match('/\d+(?= pcs)/i',$sStr,$out)?$out[0]:'';

或带有捕获组且没有先行的preg_match()

$sStr = '651267 : Spoon 128 pcs @xtra';
echo preg_match('/(\d+) pcs/i',$sStr,$out)?$out[1]:[];

或具有字符串功能的非正则表达式:

$sStr = '651267 : Spoon 128 pcs @xtra';
$trunc=stristr($sStr,' pcs',true);
echo substr($trunc,strrpos($trunc,' ')+1);

对于多次出现:

preg_match_all()与捕获组一起使用:

$sStr = '178139 : 4 Pcs pen and 2 Pcs book';
var_export(preg_match_all('/(\d+) pcs/i',$sStr,$out)?$out[1]:'fail');  // capture group

或先行使用preg_match_all()

$sStr = '178139 : 4 Pcs pen and 2 Pcs book';
var_export(preg_match_all('/\d+(?= pcs)/i',$sStr,$out)?$out[0]:'fail');

或具有数组功能的非正则表达式:

$array=explode(' ',strtolower($sStr));
var_export(array_values(array_intersect_key(array_merge([''],$array),array_flip(array_keys($array,'pcs')))));

输出:

array (
  0 => '4',
  1 => '2',
)

=>使用preg_match_all()可以获得所有匹配的数值。

=>然后使用end()从数组中获取最后一个元素。

参见示例

<?php
    //string
    $fStr = '51672 : Cup 12 Pcs';
    $sStr = '651267 : Spoon 128 pcs @xtra';
    $tStr = '2 Pcs 12 pcs 453 @xtra';

    preg_match_all('/\d+/', $tStr, $matches);
    echo "<pre>";
    echo end($matches[0]);
?>

参见演示

暂无
暂无

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

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