【问题标题】:replace string on condition - php根据条件替换字符串 - php
【发布时间】:2013-11-19 20:10:39
【问题描述】:

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

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

所以我想用 cards 替换 toys 。但仅限于不在 ques 中的 (")。

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

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

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

有人可以帮忙吗?

【问题讨论】:

    标签: php conditional-statements str-replace


    【解决方案1】:

    您需要解析字符串以识别不在引号内的区域。您可以使用支持计数的状态机或正则表达式来做到这一点。

    这是一个伪代码示例:

    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拆分字符串,每个备用区域都会用引号引起来。

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

    【讨论】:

    • 你有php例子吗?
    【解决方案2】:

    您可以使用正则表达式并使用否定环视来查找不带引号的行,然后对其进行字符串替换。

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

    例如

    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

    【讨论】:

    • thanx @Oliver,我试图运行你的例子来理解它,但它对我不起作用,你能澄清更多或另一个例子吗?
    • @Hussein 这个例子是伪代码,我有一段时间没有玩过 PHP 但逻辑仍然有效。你有没有检查我给你的rubular链接,因为它会给你视觉反馈?
    • 是的,我做到了,但我找不到让它在 php 中工作.. 它没有给出相同的结果。
    【解决方案3】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2012-06-12
      • 2021-06-19
      • 1970-01-01
      • 2019-03-31
      • 2015-11-06
      • 2021-10-08
      • 2021-10-07
      • 2021-12-20
      相关资源
      最近更新 更多