PHP 正则表达式 preg_replace 括号之间有多个值

PHP Regex preg_replace multiple values between parentheses

我正在尝试使用正则表达式搜索字符串、替换多个值并构建 URL。我之前从未使用过正则表达式(从头开始),所以有点卡住了。

该字符串作为标识符包含在 [方括号] 中。我尝试了多种方法——我不明白如何构造正则表达式或 preg_replace 方法以便能够执行多次替换,理想情况下没有很多重复的正则表达式行,但这是我正在尝试的方向:

    $string= '[mycode="gallery" type="single" id="1" data="only"]'; //INPUT

    $string = preg_replace('/\mycode="(.*)"\]/', '/mycode"', $string);
    $string = preg_replace('/\type="(.*)"\]/', 'mycode_.php', $string);
    $string = preg_replace('/\id="(.*)"\]/', '?id=', $string);
    $string = preg_replace('/\data="(.*)"\]/', '&data=', $string);

最终输出:

gallery/_mycode_single.php?id=1&data=only(也删除了 [])

我知道这目前不起作用,因为我不知道从多行编译输出的方法;任何援助将不胜感激。谢谢!

您将需要进行两层操作,首先拉动 [] 之间的所有内容,然后根据需要替换值。您可以使用 preg_replace_callback 来完成这个。

$string= '[mycode="gallery" type="single" id="1" data="only"]';
echo preg_replace_callback('/\[([^\]]+)\]/', function($match) {
    $string = preg_replace('/\h*mycode="([^"]+)"\h*/', '/mycode', $match[1]);
    $string = preg_replace('/\h*type="([^"]+)"\h*/', 'mycode_.php', $string);
    $string = preg_replace('/\h*id="([^"]+)"\h*/', '?id=', $string);
    $string = preg_replace('/\h*data="([^"]+)"\h*/', '&data=', $string);
    return $string;
}, $string);

您的正则表达式不工作有几个原因:

  1. 您的字符串未以 ]
  2. 结尾
  3. 正则表达式中的反斜杠转义或创建元字符,\d 是一个数字 \t 是一个制表符。
  4. 如果构建 URL 你不想在返回值中使用双引号
  5. 您还需要 trim 前导和尾随空格

演示:https://3v4l.org/KDD0B