[英]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.