简体   繁体   English

PHP Regex:未包装的项目

[英]PHP Regex: not wrapped items

How i can find and replace all non-wrapped items in string via PHP regular expression? 我如何通过PHP正则表达式查找和替换字符串中所有未包装的项目?

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}": 例如,我有源字符串“ 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}

How you can see, it's now work :( 怎么看,它现在可以工作了:(

您可以尝试以下方法:

$input_lines = preg_replace('/(?<!{)2(?!})/', '{3}', $input_lines);

/(?<!{)2(?!})/ will do the trick. /(?<!{)2(?!})/将解决问题。 Updated to take care of scenarios like 123} . 已更新,以照顾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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM