0

ここで問題に直面しており、ある条件下で文字列を別の文字列に置き換えようとしています。例を確認してください:

$data = '
tony is playing with toys.
tony is playing with "those toys that are not his" ';

だから私はおもちゃカードに置き換えたい. ただし、クエリ ( " )に含まれていないもののみ。

私はおもちゃであるすべての言葉を置き換える方法を知っています .

$data = str_replace("toys", "cards",$data);

しかし、( " )にないものだけを置き換えることを指定する条件を追加する方法がわかりません。

誰でも助けてくれますか?

4

3 に答える 3

0

正規表現を使用し、否定的なルックアラウンドを使用して引用符のない行を見つけ、その上で文字列の置換を行うことができます。

^((?!\"(.+)?toys(.+)?\").)*

例えば

preg_match('/^((?!\"(.+)?toys(.+)?\").)*/', $data, $matches);
$line_to_replace = $matches[0];
$string_with_cards = str_replace("toys", "cards", $line_to_replace);

または、複数の一致がある場合は、配列を反復処理することができます。

http://rubular.com/r/t7epW0Tbqi

于 2013-11-07T23:13:03.437 に答える
0

文字列を解析して、引用符で囲まれていない領域を特定する必要があります。これは、カウントをサポートするステート マシンまたは正規表現を使用して実行できます。

擬似コードの例を次に示します。

typedef Pair<int,int> Region;
List<Region> regions;

bool inQuotes = false;
int start = 0;
for(int i=0;i<str.length;i++) {
    char c = str[i];
    if( !inQuotes && c == '"' ) {
        start = i;
        inQuotes = true;
    } else if( inQuotes && c == '"' ) {
        regions.add( new Region( start, i ) );
        inQuotes = false;
    }

}

次に、文字列を に従って分割しregionsます。各代替リージョンは引用符で囲まれます。

読者への挑戦: エスケープされた引用符を処理するように取得してください :)

于 2013-11-07T23:11:27.250 に答える
-1

これを行う簡単な方法の 1 つを次に示します。引用符を使用して文字列を分割/展開します。結果の配列の最初の ( 0-index ) 要素と各偶数番号のインデックスは、引用符で囲まれていないテキストです。奇数は引用符で囲みます。例:

Test "testing 123" Test etc.
^0    ^1          ^2

次に、偶数番目の配列要素のみで魔法の言葉 (toys) を置換 (cards) に置き換えます。

サンプルコード:

function replace_not_quoted($needle, $replace, $haystack) {
    $arydata = explode('"', $haystack);

    $count = count($arydata);
    for($s = 0; $s < $count; $s+=2) {
        $arydata[$s] = preg_replace('~'.preg_quote($needle, '~').'~', $replace, $arydata[$s]);
    }
    return implode($arydata, '"');
}

$data = 'tony is playing with toys.
tony is playing with toys... "those toys that are not his" but they are "nice toys," those toys';

echo replace_not_quoted('toys', 'cards', $data);

したがって、サンプルデータは次のとおりです。

tony is playing with toys.
tony is playing with toys... "those toys that are not his" but they are "nice toys," those toys

アルゴリズムは期待どおりに機能し、以下を生成します。

tony is playing with cards.
tony is playing with cards... "those toys that are not his" but they are "nice toys," those cards
于 2013-11-08T01:10:54.460 に答える