检查多个字符串是否有值,并返回有值的字符串


Check multiple strings for value and return the one with value

我有以下代码:

preg_match("/Total Payout:(.*)/", $comments, $airbnb_total_payout);
preg_match("/Payout:('s+[^'s]+)/", $comments, $airbnb_per_night); //price per night
preg_match("/Total reservation amount:('s+[^'s]+)/", $comments, $booking_total); //booking price

这三个中只有一个有值。我可以写什么函数来检查:

$airbnb_total_payout[1]
$airbnb_per_night[1] 
$booking_total[1]

哪一个有值?并且只返回它。由于

您已经获得了代码。你可以把它扔到函数中。

function getValue ($comments) {
    preg_match("/Total Payout:(.*)/", $comments, $airbnb_total_payout); 
     if (strlen( $airbnb_total_payout[1]) > 0)
        return  $airbnb_total_payout[1] ;
    preg_match("/Payout:('s+[^'s]+)/", $comments, $airbnb_per_night); //price per night 
     if (strlen( $airbnb_per_night[1]) > 0)
        return  $airbnb_per_night[1] ;
    preg_match("/Total reservation amount:('s+[^'s]+)/", $comments, $booking_total); //booking price
     if (strlen($booking_total[1]) > 0)
        return $booking_total [1];
    return false;
}

(From phone so watch for errors)

您可以尝试一系列if语句:

function getValue($comments,$airbnb_total_payout,$airbnb_per_night,$booking_total) {
     if(preg_match("/Total Payout:(.*)/", $comments, $airbnb_total_payout)) return $airbnb_total_payout[1];
     if(preg_match("/Payout:('s+[^'s]+)/", $comments, $airbnb_per_night)) return $airbnb_per_night[1];
     if(preg_match("/Total reservation amount:('s+[^'s]+)/", $comments, $booking_total)) return $booking_total[1];
     return false; // Return value if none of the conditions are met above.
}

调用函数使用:

$myValueResult = getValue($comments,$airbnb_total_payout,$airbnb_per_night,$booking_total);

$myValueResult将拥有函数的结果值。

试试这个:

    if($airbnb_total_payout[1] != ""){
        echo $airbnb_total_payout[1];
    }elseif($airbnb_per_night[1] != ""){
        echo $airbnb_per_night[1] ;
    }elseif($booking_total[1] != ""){
        echo $booking_total;
    }else{
        echo "Nothing has a value";
    }