繁体   English   中英

PHP Regex:未包装的项目

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

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