2

タイトルは、私が達成しようとしていることのほとんどを要約しています。

アルファベットの文字、数字、または「)」や「*」などの文字で構成される文字列があります。また、「25...123.50」など、3 つのドット「...」で区切られた数値文字列を含めることもできます。

この文字列の例は次のとおりです。

peaches* 25...123.50 +("apples")また-(peaches*) apples* 25...123.50

今、私がやりたいのは、3 つのドットの前後の数字をキャプチャすることです。そのため、2 つの変数25123.50. 次に、数値を除外した文字列になるように文字列をトリミングしたいと思います。

peaches* +("apples")また-(peaches*) apples*

したがって、本質的に:

$string = 'peaches* 25...123.50 +("apples")';
if (preg_match("/\.\.\./", $string ))
{
    # How do i get the left value (could or could not be a decimal, using .)
    $from = 25; 
    # How do i get the right value (could or could not be a decimal, using .)
    $to = 123.50;
    # How do i remove the value "here...here" is this right?
    $clean = preg_replace('/'.$from.'\.\.\.'.$to.'/', '', $string);
    $clean = preg_replace('/  /', ' ', $string);
}

この複雑なタスクを実行するための最善の方法について、誰かが私に情報を提供できれば、非常にありがたいです! 提案、アドバイス、入力、フィードバック、またはコメントは大歓迎です。ありがとうございます!

4

2 に答える 2

1

疑似コード

ループ内:

"..." に対してstrposを実行し、その位置でsubstrを実行します。次に、その部分文字列の末尾から (1 文字ずつ) 戻り、それぞれがis_numericperiodかを確認します。最初の非数値/非ピリオドの出現で、元の文字列の先頭からそのポイントまでの部分文字列を取得します (一時的に保存します)。次に、反対方向の is_numeric またはピリオドのチェックを開始します。部分文字列を取得し、保存した他の部分文字列に追加します。繰り返す。

これは正規表現ではありませんが、それでも同じ目標を達成します。

いくつかのphp

$my_string = "blah blah abc25.4...123.50xyz blah blah etc";
$found = 1;

while($found){

    $found = $cursor = strpos($my_string , "...");

    if(!empty($found)){

        //Go left
        $char = ".";
        while(is_numeric($char) || $char == "."){
            $cursor--;
            $char = substr($my_string , $cursor, 1);
        } 
        $left_substring = substr($my_string , 1, $cursor);

        //Go right
        $cursor = $found + 2;
        $char = ".";
        while(is_numeric($char) || $char == "."){
            $cursor++;
            $char = substr($my_string , $cursor, 1);
        } 
        $right_substring = substr($my_string , $cursor);

        //Combine the left and right
        $my_string = $left_substring . $right_substring;
    }
}

echo $my_string;
于 2013-05-22T02:32:42.690 に答える