How i can find and replace all non-wrapped items in string via PHP regular expression?
For example, I have source string "2a{2}b2ac1{1}a{2}aab12{1}b2a{1}2" and try find symbol "2", which are not covered by "{" and "}", after this replace it with "{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}
How you can see, it's now work :(
您可以尝试以下方法:
$input_lines = preg_replace('/(?<!{)2(?!})/', '{3}', $input_lines);
/(?<!{)2(?!})/
will do the trick. Updated to take care of scenarios like 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}"
Explanation:
/ # Beginning delimiter
(?<!{) # Lookbehind for anything other than {
2 # Match 2
(?!}) # Lookahead for anything other than }
/ # Ending delimiter
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.