[英]replace string on condition - php
我在这里遇到问题,尝试在某种情况下用另一个字符串替换。 检查示例:
$data = '
tony is playing with toys.
tony is playing with "those toys that are not his" ';
所以我想用卡片代替玩具 。 但只有不在ques( “ )中的内容。
我知道如何替换所有玩具的单词。
$data = str_replace("toys", "cards",$data);
但我不知道如何添加一个条件,该条件指定仅替换不在( “ )中的条件。
有人可以帮忙吗?
您需要分析字符串以识别不在引号内的区域。 您可以使用支持计数的状态机或正则表达式来执行此操作。
这是一个伪代码示例:
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
分割字符串,每个备用区域都用引号引起来。
对读者的挑战:掌握它以便处理转义的引号:)
您可以使用正则表达式,并使用负查找法查找没有引号的行,然后对此进行字符串替换。
^((?!\"(.+)?toys(.+)?\").)*
例如
preg_match('/^((?!\"(.+)?toys(.+)?\").)*/', $data, $matches);
$line_to_replace = $matches[0];
$string_with_cards = str_replace("toys", "cards", $line_to_replace);
或者,如果有多个匹配项,则可能要遍历数组。
这是一种简单的方法。 使用引号分隔/分解字符串。 结果数组中的第一个( 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.