在 PHP 中,我需要替换变量值周围的固定前缀和后缀。
除非该值是字符串,否则该值周围的引号将被删除。
[blargh="5"] => <potato chips=#5#>
[blargh="97"] => <potato chips=#97#>
[blargh="StackOverflow"] => <potato chips=#"StackOverflow"#>
我知道我可以使用 preg_replace()
来执行此操作,但我不知道如何操作。
最佳答案
分支重置:(?| ... )
你的问题中棘手的部分是 "StackOverflow"
我们在替换中包含引号,但对于 "87"
我们剥掉它们。不用担心,分支重置功能可以很好地处理这个问题。
在 Regex Demo ,请参阅底部的替换内容。
示例 PHP 代码
$yourstring = '[blargh="5"] [blargh="97"] [blargh="StackOverflow"]';
$replaced = preg_replace('~\[blargh=(?|"(\d+)"|("[^"]*"))\]~',
'<potato chips=#\1#>',
$yourstring);
echo $replaced;
输出
<potato chips=#5#> <potato chips=#97#> <potato chips=#"StackOverflow"#>
我们的搜索正则表达式:
\[blargh=(?|"(\d+)"|("[^"]*"))\]
我们的替换字符串
<potato chips=#\1#>
说明
-
\[blargh=
匹配文字字符 - 在分支中重置
(?| .... )
,所有组都捕获到组 1 -
"(\d+)"
捕获第 1 组引号内的数字(但不捕获引号) - 或
|
-
("[^"]*")
捕获完整"quoted string"
至组 1 -
\]
匹配右括号 - 在替换中,
<potato chips=#\1#>
,\1
是对组 1 的反向引用
引用
关于php - 替换,但仅在某些情况下包含分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25050387/