Search code examples
phpwordpresssubstrstrpos

Not returning a value in PHP in SUBSTR


Anyone know why this is not returning a value?

Example $item2['data'] where it = UPC
//===================================================//
Author:  Bob Smith  Orig. Published:  December 12, 1980
Format:  Softcover  UPC:  5960605543-04811 Price:  $6.99

//======================================================//
Example $item2['data'] where it = ISBN
//======================================================//
Author:  Jane Smith  Orig. Published:  December 1, 1985
Format:  Hardcover  ISBN #: 978-0-7851-5773-1 Price:  $26.99

//======================================================//
The Code
//======================================================//

$find_stockcode = $item2['data'];

$pos = strpos($find_stockcode, "ISBN");

if ($pos === false) 
{
    $pos = strpos ($find_stockcode, "UPC");
    if($pos === false) 
    {
        $arr = str_split('ABCDEFGHIJKLMNOP0123456789'); 
        shuffle($arr);
        $arr = array_slice($arr, 0, 16); 
        $str = implode('', $arr);
        $stock_num = $str;
    } else  {
          $stock_num = substr($pos, 5, 16);}
} else {
        $stock_num = substr($pos, 8,16); }

$upc = $stock_num;

if $find_stockcode returns UPC then $upc should be: 5960605543-04811

if $find_stockcode returns ISBN then $upc should be: 978-0-7851-5773-1

if $find_stockcode does not find UPC or ISBN then $upc should be a random 16 alpha-numeric string.


Solution

  • I believe the best approach for what you're trying to do here is a regular expression.

    For your specific task, this should do it:

    $number = preg_match("/((UPC)|(ISBN))[^0-9-]+([0-9-]+)/", $input, $fields);
    
    if (count($fields) > 1) {
        $upc = $fields[4];
    } else {
        $arr = str_split('ABCDEFGHIJKLMNOP0123456789'); 
        shuffle($arr);
        $arr = array_slice($arr, 0, 16); 
        $upc = implode('', $arr);
    }
    

    If you want to know which number code was found, use $fields[1].

    Good luck