[英]PHP Regex: not wrapped items
我如何通過PHP正則表達式查找和替換字符串中所有未包裝的項目?
例如,我有源字符串“ 2a {2} b2ac1 {1} a {2} aab12 {1} b2a {1} 2”,並嘗試找到符號“ 2”,它們沒有被“ {”和“}”覆蓋,之后將其替換為“ {3}”:
$input_lines = "2a{2}b2ac1{1}a{2}aab12{1}b2a{1}2";
$regex = "/[^\{](2)[^\}]/";
$input_lines = preg_replace("/[^\{](2)[^\}]/", "{3}", $input_lines);
echo $input_lines;
// 2a{2}{3}c1{1}a{2}aab{3}1}{3}{1{3}
怎么看,它現在可以工作了:(
您可以嘗試以下方法:
$input_lines = preg_replace('/(?<!{)2(?!})/', '{3}', $input_lines);
/(?<!{)2(?!})/
將解決問題。 已更新,以照顧123}
類的情況。
$input_lines = '2a{2}b2ac1{1}a{2}aab12{1}b2a{1}2';
$input_lines = preg_replace('/(?<!{)2(?!})/', '{3}', $input_lines);
var_dump($input_lines);
// string(42) "{3}a{2}b{3}ac1{1}a{2}aab1{3}{1}b{3}a{1}{3}"
說明:
/ # Beginning delimiter
(?<!{) # Lookbehind for anything other than {
2 # Match 2
(?!}) # Lookahead for anything other than }
/ # Ending delimiter
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.