-1

ユーザーは のような文字列を入力します151+328。ユーザーが2つの数値の間の操作を入力したことを検出して返す機能が必要です。どうやってするの?正規表現を使用して最初の部分を行う方法を知っています(つまり[0-9]+\+[0-9]、2番目の部分についての手がかりがありません.

tldr:

function('10+296', '+', 1)='10'    
function('10+296', '+', 2)='296'    
function('perpderpherp', 'derp', 2)='herp'
4

2 に答える 2

1

この関数は正規表現を使用して、文字列が [0-9]+[0-9] の形式であることを確認し、分解して一部を返します。

function splitAndReturn($str, $delimiter, $part) {
    $pattern = '/^\d+\+\d+$/';
    if (preg_match($pattern, $str)) {
        $parts = explode($delimiter, $str);
        return $parts[$part-1];
    }
    return false;
}

echo splitAndReturn('10+296', '+', 1); //=10
echo splitAndReturn('10+296', '+', 2); //=296
echo splitAndReturn('potatocarrotbanana', 'carrot', 1); // returns false because it doesn't comply with the "detect only [0-9]+[0-9]" rule you stated.

この関数はexplode、区切り文字で文字列を分割し、任意の部分を返すために使用します。

function splitAndReturn($str, $delimiter, $part) {
    $parts = explode($delimiter, $str);
    return $parts[$part-1];
}

echo splitAndReturn('10+296', '+', 1); //=10
echo splitAndReturn('10+296', '+', 2); //=296
echo splitAndReturn('potatocarrotbanana', 'carrot', 1); //='potato'

区切り文字が存在しない場合は、元の文字列が返されます。

于 2012-10-21T18:26:29.727 に答える
0

\d+\+\d+検出number + numberし、またはしないword + wordか、word + numberまたはnumber + word

于 2012-10-21T18:58:48.323 に答える