Domanda

Come potrei meglio raggiungere i seguenti:

Vorrei trovare e sostituire i valori in una stringa in PHP meno che non siano tra virgolette singole o doppie.

EG.

$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;

stringa echo'd deve restituire:

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

Grazie in anticipo per il vostro aiuto.

È stato utile?

Soluzione

Si potrebbe dividere la stringa in citate parti / non quotate e str_replace poi chiamata solo sulle parti non quotate. Ecco un esempio utilizzando 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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top