php - 替换,但仅在某些情况下包含分隔符

标签 php regex string

在 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/

相关文章:

xml - xquery 多 if-else 语句

java - 检查句子是否包含某些单词

string - SKLabel.text 整数不更新 - swift

php - 在 PHP 中增加日期的最简单方法?

php - 如何在 JS 脚本中正确回显 PHP 变量?

php - 验证 Google 电子邮件是否在 ajax 请求中发送

javascript - 正则表达式提取 img src javascript

php PDO插入错误

javascript - RegEx - 允许在固定长度字符串的开头和结尾处存在空格

php - 提取字符串中的每一次出现