简体   繁体   中英

Get last numeric before certain word in PHP String

I've php string that contain pcs , Pcs , or PCS .

How do I can get the last numeric before the word psc , Pcs , or PCS ?

Example:

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

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

Is it possible using regex?

Anyhelp will be appreciated. Thanks

UPDATE:

The case above has been solved by the answer below. But how do I can handle if there's more than one word pcs inside the string. For example

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

here's a test

You can use preg_match() to generate a fullstring match with a lookahead:

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

Or preg_match() with a capture group and no lookahead:

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

Or non-regex with string functions:

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

For multiple occurrences:

use preg_match_all() with a capture group:

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

or use preg_match_all() with a lookahead:

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

or non-regex with array functions:

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

Output:

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

=> Using preg_match_all() you can get all matched numeric value.

=> Then get last element from array using end() .

See example,

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

See Demo .

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