0

最後の括弧にあるものをすべて取り、括弧なしで新しい変数に入れる文字列関数を作成する必要があります。この場合、UPS Next Day Air です。

$oldVar = 'United Parcel Service (1 pkg x 4.00 lbs total) (UPS Next Day Air)';
$newVar = 'UPS Next Day Air';

ありがとう!、

4

4 に答える 4

1
<?php
$oldVar = 'United Parcel Service (1 pkg x 4.00 lbs total) (UPS Next Day Air)';
$newVar = preg_replace('/.+\((.+?)\)[^\)]*$/', '$1', $oldVar);    
?>
于 2013-08-07T23:56:53.077 に答える
1
<?php
$oldVar = 'United Parcel Service (1 pkg x 4.00 lbs total) (UPS Next Day Air)';
$newVar = '';
if (preg_match('/.*\((.+)\)/s', $oldVar, $matches))
{
    $newVar = $matches[1];
} else {
    // the input $oldVar did not contain a matching string
}

var_dump($newVar);
于 2013-08-07T23:54:07.410 に答える
0

次のコードは$newVar、一致する括弧がある場合は正しい文字列に設定し、それ以外の場合は to に設定$oldVarfalseます。

$oldVar = 'United Parcel Service (1 pkg x 4.00 lbs total) (UPS Next Day Air)';
$posLastOpeningParenthesis = strrpos($oldVar, '(');
if ($posLastOpeningParenthesis === false) {
    $newVar = false;
}
else {
    $posLastOpeningParenthesis++; // move the position to behind the opening parenthesis
    $posLastClosingParenthesis = strpos($oldVar, ')', $posLastOpeningParenthesis);
    if ($posLastClosingParenthesis === false) {
        $newVar = false;
    }
    else {
        $newVar = substr($oldVar, $posLastOpeningParenthesis, $posLastClosingParenthesis - $posLastOpeningParenthesis);
    }
}
于 2013-08-08T00:36:34.823 に答える