How to replace words outside double and single quotes

For a custom script parser in PHP, I would like to replace a few words in a multi-line string containing double and single quotes. However, only text outside can be replaced .

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

For example, I would like to replace "apple" with "pear", but only outside the sentences of the sentence. Thus, in this case only the "apple" inside the "Many apples fall from the trees" will be targeted.

The above result will give the following result:

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

How can i achieve this?

+5
source share
4 answers

This function does the trick:

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 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 another apple over there!"    
'Seedling apples are an example of "extreme heterozygotes".'
+6

:

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

+1

Just think: create a temporary line by deleting the quoted parts, replace what you need, and then add the quoted parts that you deleted.

0
source

You can use preg_replace using a regular expression to replace the words inside ""

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

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

You can add more searchable objects by adding another RegEx to $ search, and replace the other line with $ replace

This RegEx uses lookahead and lookbehind to find out if the search string is inside "

0
source

All Articles