在条件上替换字符串 - php

时间:2013-11-07 23:04:28

标签: php conditional-statements str-replace

我在这里面临一个问题,试图在一个条件下用另一个替换字符串。 检查示例:

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

所以我想用替换玩具。但只有哪些不是问题()。

我知道如何替换所有玩具的单词。

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

但我不知道如何添加一个条件,该条件指定只替换不在()中的那个。

任何人都可以帮忙吗?

3 个答案:

答案 0 :(得分: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分割字符串,每个备用区域都在引号中。

读者的挑战:得到它以便处理转义引号:)

答案 1 :(得分:0)

您可以使用正则表达式并使用否定的外观来查找没有引号的行,然后对其执行字符串替换。

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

e.g。

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

答案 2 :(得分:-1)

这是一种简单的方法。使用引号分割/爆炸您的字符串。结果数组中的第一个(0 - 索引)元素和每个偶数编号索引是不带引号的文本;奇数是在引号内。例如:

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

然后,只用偶数数组元素中的替换(卡片)替换魔术字(玩具)。

示例代码:

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