1

次のことをどのように達成するのが最善でしょうか:

一重引用符または二重引用符で囲まれていない限り、PHP の文字列内の値を検索して置換したいと考えています。

例えば。

$string = 'The quoted words I would like to replace unless they are "part of a quoted string" ';

$terms = array(
  'quoted' => 'replaced'
);

$find = array_keys($terms);
$replace = array_values($terms);    
$content = str_replace($find, $replace, $string);

echo $string;

echo'd 文字列は次を返す必要があります。

'The replaced words I would like to replace unless they are "part of a quoted string" '

よろしくお願いします。

4

1 に答える 1

1

文字列を引用符で囲まれた部分と引用されていない部分に分割し、引用符で囲まれていない部分のみを呼び出すことができますstr_replace。を使用した例を次に示しpreg_splitます。

$string = 'The quoted words I would like to replace unless they are "part of a quoted string" ';
$parts = preg_split('/("[^"]*"|\'[^\']*\')/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
for ($i = 0, $n = count($parts); $i < $n; $i += 2) {
    $parts[$i] = str_replace(array_keys($terms), $terms, $parts[$i]);
}
$string = implode('', $parts);
于 2010-11-17T21:25:33.283 に答える