替换条件字符串-PHP [英] replace string on condition - php

查看:63
本文介绍了替换条件字符串-PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里面临一个问题,尝试在某种情况下用另一个字符串替换。
检查示例:

i am facing an issue here , trying to replace string with another under a condition. check the example :

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

所以我想用代替玩具 >。但只有那些不在疑问句中的( )。

so i want to replace toys with cards . but only which is NOT in ques (").

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

i know how to replace all words that are toys .

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

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

but i don't know how to add a condition which specifies to replace only the one's which are not in the (").

有人可以帮忙吗?

推荐答案

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

Here's one simple way to do it. Split/explode your string using quotation marks. The first (0-index) element and each even-numbered index in the resulting array is unquoted text; the odd numbers are inside quotes. Example:

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

然后,仅将偶数数组元素中的魔术字(玩具)替换为替换(卡)即可。

Then, just replace the magic words (toys) with the replacement (cards) in only the even-numbered array elements.

示例代码:

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

因此,此处的示例数据为:

So, here, the sample data is:

tony is playing with toys.
tony is playing with toys... "those toys that are not his" but they are "nice toys," those toys

该算法按预期工作并产生:

The algorithm works as expected and produces:

tony is playing with cards.
tony is playing with cards... "those toys that are not his" but they are "nice toys," those cards

这篇关于替换条件字符串-PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆