【问题标题】:Replace a string that matches a pattern using preg_replace_callback使用 preg_replace_callback 替换与模式匹配的字符串
【发布时间】:2021-01-26 13:23:19
【问题描述】:

我想用给定字符串中的子字符串“XY”替换模式“binary_function([x,y])”的出现。

我让它使用以下代码:

// $string is the string to be searched
$string = preg_replace_callback('/binary_function\(\[(\S),(\S)\]\)/', function ($word) {
        $result = strtoupper($word[1]) . strtoupper($word[2]);              
        return $result;
        }, $string);

但是,我还希望它用子字符串“X1Y1”替换“binary_function([x1,y1])”,以及方括号内的任何长度的参数,例如[x11,y12]、[var1,var2] 等

我试过了:

// $string is the string to be searched
$string = preg_replace_callback('/binary_function\(\[(\S+),(\S+)\]\)/', function ($word) {
        $result = strtoupper($word[1]) . strtoupper($word[2]);              
        return $result;
        }, $string);

但它不起作用。

有人可以帮忙吗?

谢谢。

【问题讨论】:

  • '/binary_function\(\[([^][\s,]+),([^][\s,]+)]\)/'
  • 太棒了 :-) 非常感谢。

标签: php regex preg-replace-callback


【解决方案1】:

你可以使用

'/binary_function\(\[([^][\s,]+),([^][\s,]+)]\)/'

regex demo

正则表达式详细信息

  • binary_function\(\[ - binary_function([ 文字
  • ([^][\s,]+) - 第 1 组:除][、空格和, 之外的任何一个或多个(由于+)字符
  • , - 逗号
  • ([^][\s,]+) - 第 2 组:除 ][、空格和 , 之外的任何一个或多个(由于 +)字符
  • ]\) - ]) 字符串。

【讨论】:

  • 非常感谢您的详细解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 2014-09-03
  • 2013-10-24
  • 2012-09-23
  • 1970-01-01
  • 2014-08-20
  • 2022-01-02
相关资源
最近更新 更多