搜索并替换多行字符串中的所有行

Search and replace all lines in a multiline string

我有一个包含大列表的字符串,其中的项目命名如下:

str = "f05cmdi-test1-name1
f06dmdi-test2-name2";

所以前4个字符是随机字符。我想要这样的输出:

'mdi-test1-name1',
'mdi-test2-name2',

如您所见,字符串中的第一个字符需要替换为 ' 并且每一行都需要以 ' 结尾,

如何将上面的字符串改成下面的字符串?我已经为我们的 'strstr' 和 'str_replace' 尝试过,但我无法让它工作。如果我成功了,我会节省很多时间。

感谢大家的帮助!

EDIT : I deleted the above since the following method is better and more reliable and can be used for any possible combination of four characters.

如果有一百万种不同的可能性作为起始字符,我该怎么办?

在您的具体示例中,我看到唯一的 space 位于完整字符串之间(完整字符串 = "f05cmdi-test1-name1"

所以:

str = "f05cmdi-test1-name1 f06dmdi-test2-name2";
$result_array = [];
// Split at the spaces
$result = explode(" ", $str);
foreach($result as $item) {
    // If four random chars take string after the first four random chars 
    $item = substr($item, 5); 
    $result_array = array_push($result_arrray, $item);
}

导致:

$result_array = [
    "mdi-test1-name1",
    "mdi-test2-name2",
    "....."
];

如果您想要 :

样式的单个字符串

"'mdi-test1-name1','mdi-test2-name2','...'"

那么您可以简单地执行以下操作:

$result_final = "'" . implode("','" , $result_array) . "'";

这在相当简单的正则表达式模式中是可行的

<?php

$str = "f05cmdi-test1-name1
f05cmdi-test2-name2";

$str = preg_replace("~[a-z0-9]{1,4}mdi-test([0-9]+-[a-z0-9]+)~", "'mdi-test\1',", $str);
echo $str;

根据您更具体的需求进行更改

这是完成这项工作的一种方法:

$input = "f05cmdi-test1-name1
f05cmdi-test2-name2";

$result = preg_replace("/.{4}(\S+)/", "'',", $input);
echo $result;

其中 \S 代表非 space 字符。