5

PHPのカスタムスクリプトパーサーの場合、二重引用符と一重引用符を含む複数行の文字列内のいくつかの単語を置き換えたいと思います。ただし、引用符の外側にあるテキストのみを置き換えることができます。

Many apples are falling from the trees.    
"There's another apple over there!"    
'Seedling apples are an example of "extreme heterozygotes".'

たとえば、「apple」を「pear」に置き換えたいのですが、引用文の外側に限られます。したがって、この場合、「多くのリンゴが木から落ちている」内の「リンゴ」のみが対象になります。

上記の場合、次の出力が得られます。

Many pears are falling from the trees.    
"There's another apple over there!"    
'Seedling apples are an example of "extreme heterozygotes".'

どうすればこれを達成できますか?

4

4 に答える 4

5

この関数はトリックを行います:

function str_replace_outside_quotes($replace,$with,$string){
    $result = "";
    $outside = preg_split('/("[^"]*"|\'[^\']*\')/',$string,-1,PREG_SPLIT_DELIM_CAPTURE);
    while ($outside)
        $result .= str_replace($replace,$with,array_shift($outside)).array_shift($outside);
    return $result;
}

動作方法引用符で囲まれた文字列で分割されますが、これらの引用符で囲まれた文字列が含まれます。これにより、配列内の引用符で囲まれていない文字列、引用されていない文字列、引用されていない文字列、引用されていない文字列などを交互に使用できます (引用符で囲まれていない文字列の一部は空白の場合があります)。次に、単語を置換する場合と置換しない場合を交互に繰り返すため、引用符で囲まれていない文字列のみが置換されます。

あなたの例で

$text = "Many apples are falling from the trees.    
        \"There's another apple over there!\"    
        'Seedling apples are an example of \"extreme heterozygotes\".'";
$replace = "apples";
$with = "pears";
echo str_replace_outside_quotes($replace,$with,$text);

出力

Many pears are falling from the trees.    
"There's another apple over there!"    
'Seedling apples are an example of "extreme heterozygotes".'
于 2012-06-07T09:26:47.577 に答える
1

私はこれを思いついた:

function replaceOutsideDoubleQuotes($search, $replace, $string) {
    $out = '';
    $a = explode('"', $string);
    for ($i = 0; $i < count($a); $i++) {
        if ($i % 2) $out .= $a[$i] . '"';
        else $out .= str_replace($search, $replace, $a[$i]) . '"';
    }
    return substr($out, 0, -1);
}

ロジックは次のとおりです。文字列を二重引用符で分解するため、返される文字列配列の奇数要素は引用符の外側のテキストを表し、偶数要素は二重引用符内のテキストを表します。

ですから、元の部品と交換された部品を交互に連結することで、出力を構築できますよね?

ここでの作業例: http://codepad.org/rsjvCE8s

于 2012-06-07T09:22:43.617 に答える
0

ちょっと考えてみてください。引用部分を削除して一時的な文字列を作成し、必要なものを置き換えてから、削除した引用部分を追加します。

于 2012-06-07T09:19:16.447 に答える
0

preg_replace を使用して、正規表現を使用して " " 内の単語を置き換えることができます。

$search  = array('/(?!".*)apple(?=.*")/i');
$replace = array('pear');
$string  = '"There\'s another apple over there!" Seedling apples are an example of "extreme heterozygotes".';

$string = preg_replace($search, $replace, $string);

$search に別の RegEx を追加し、$replace に別の置換文字列を追加することで、検索可能なオブジェクトをさらに追加できます。

この RegEx は、先読みと後読みを使用して、検索された文字列が " " 内にあるかどうかを調べます。

于 2012-06-07T09:25:09.090 に答える