PhpStorm 在两个字符串之间多次搜索和替换

PhpStorm search and replace multiple times between two strings

在 PhpStorm IDE 中,使用搜索和替换功能,我试图将 .jpg 添加到 $colorsfiles = [ 之后和结束 [= 之前​​的引号之间的所有字符串中17=]。

$colorsfiles = ["Blue", "Red", "Orange", "Black", "White", "Golden", "Green", "Purple", "Yellow", "cyan", "Gray", "Pink", "Brown", "Sky Blue", "Silver"];

如果 "abc" 不在 $colorsfiles = [] 之间,则应该没有替换。

我使用的正则表达式是

$colorsfiles = \[("(\w*?)", )*

并替换字符串为

$colorsfiles = [".jpg"]

当前结果是

$colorsfiles = ["Brown.jpg"]"Sky Blue", "Silver"];

虽然预期输出是

$colorsfiles = ["Blue.jpg", "Red.jpg", "Orange.jpg", "Black.jpg", "White.jpg", "Golden.jpg", "Green.jpg", "Purple.jpg", "Yellow.jpg", "cyan.jpg", "Gray.jpg", "Pink.jpg", "Brown.jpg", "Sky Blue.jpg", "Silver.jpg"];    

为什么你需要正则表达式?一个简单的 array_map() 就可以解决问题。

<?php
function addExtension($color)
{
    return $color.".jpg";
}
$colorsfiles = ["Blue", "Red", "Orange", "Black", "White", "Golden", "Green", "Purple", "Yellow", "cyan", "Gray", "Pink", "Brown", "Sky Blue", "Silver"];
$colorsfiles_with_extension = array_map("addExtension", $colorsfiles);
print_r($colorsfiles_with_extension);
?>

编辑: 我已经在我的 PhpStorm 上测试过了,让我们像这样

搜索:

"([a-zA-Z\s]+)"

replace_all:

".jpg"

你应该说你在 IDE

上试用

即使我不使用 PHPStorm,我也会发布在我的 NetBeans 上测试过的解决方案。

查找:"([\w ]+)"([\,\]]{1})
替换:"\.jpg"

您可以使用

(\G(?!^)",\s*"|$colorsfiles\s*=\s*\[")([^"]+)

并替换为 .jpg。参见 this regex demo

正则表达式匹配 $colorsfiles = [" 或前一个匹配的结尾后跟 ",",同时将这些文本捕获到第 1 组(稍后用 </code> 占位符引用),然后捕获到第 2 组(稍后用 <code> 表示)除双引号外的一个或多个字符。

详情

  • (\G(?!^)",\s*"|$colorsfiles\s*=\s*\[") -
    • \G(?!^)",\s*" - 上一场比赛结束 (\G(?!^)),", 子字符串,0+ 个空格 (\s*) 和一个 " 字符
    • | - 或
    • $colorsfiles\s*=\s*\[" - $colorsfiles, 0+ 空格 (\s*), =, 0+ 空格, [" (注意 $[ 必须转义以匹配文字字符)
  • ([^"]+) - 捕获第 2 组:除 "(否定字符 class、[^"])之外的一个或多个 (+) 个字符