最後の括弧にあるものをすべて取り、括弧なしで新しい変数に入れる文字列関数を作成する必要があります。この場合、UPS Next Day Air です。
$oldVar = 'United Parcel Service (1 pkg x 4.00 lbs total) (UPS Next Day Air)';
$newVar = 'UPS Next Day Air';
ありがとう!、
<?php
$oldVar = 'United Parcel Service (1 pkg x 4.00 lbs total) (UPS Next Day Air)';
$newVar = preg_replace('/.+\((.+?)\)[^\)]*$/', '$1', $oldVar);
?>
<?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);
次のコードは$newVar
、一致する括弧がある場合は正しい文字列に設定し、それ以外の場合は to に設定$oldVar
しfalse
ます。
$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);
}
}