說明
我會先分割字符串攻擊這個問題分成要麼引用或不帶引號的字符串組。
然後通過匹配進行迭代,如果填充了組1,則該字符串被引用,因此只需替換捕獲組0即可進行簡單替換。如果未填充捕獲組1,則跳至下一個匹配項。
在每一次迭代中,你都會想要建立一個新的字符串。
由於分割字符串是困難的部分,我會用這個表達式:
("[^"]*")|[^"]*
例
示例文字
"mission podcast" modcast A B C "D E F"
個
代碼
PHP Code Example:
<?php
$sourcestring="your source string";
preg_match_all('/("[^"]*")|[^"]*/i',$sourcestring,$matches);
echo "<pre>".print_r($matches,true);
?>
捕捉組
$matches Array:
(
[0] => Array
(
[0] => "mission podcast"
[1] => modcast A B C
[2] => "D E F"
[3] =>
)
[1] => Array
(
[0] => "mission podcast"
[1] =>
[2] => "D E F"
[3] =>
)
)
PHP實例
這PHP腳本將只替換引號中的字符串內的空間。
工作例如:http://ideone.com/jBytL3
代碼
<?php
$text ='"mission podcast" modcast A B C "D E F"';
preg_match_all('/("[^"]*")|[^"]*/',$text,$matches);
foreach($matches[0] as $entry){
echo preg_replace('/\s(?=.*?")/ims','~~new~~',$entry);
}
輸出
"mission~~new~~podcast" modcast A B C "D~~new~~E~~new~~F"
那麼你到目前爲止嘗試過什麼? –
你能提供更多的例子,而不是'find/vol_stor/8s8a912hj1 | grep「」mission \ | podcast「」| grep「modcast」'?至少2株將是多大的幫助 – Angga
嗯,我還沒有嘗試任何事情,因爲我不知道如何保護範圍內匹配字符串的一部分,只有更換它們的括號內的字中有什麼。所以,我願意接受各種建議:) –