如何使用正则表达式替换字符串中出现的路径中的 ID

How to replace ID in the path that appears in a string using regex

示例

$string = "This is the paragraph which also contains link http://example.com/document/EN010001-0001, now this is some text after the link";

考虑到上面的例子,其中 link 可以出现在字符串的任何地方,我想用不同的 ID 替换这个 EN010001-0001,例如EN010003-0001.

我知道我们可以使用 preg_replace,有人可以帮我找出适合这种情况的正则表达式吗?

编辑#1

Link http://example.com/document/ 是静态的,它显示在字符串中。

编辑 #2

   preg_replace("http://example.com/document/([-\w]+)", 'EN010003-0001', $string);

我试过了但是收到了警告:

Warning: preg_replace(): Delimiter must not be alphanumeric or backslash

如果您的字符串开头始终相同,您可以想出以下正则表达式(使用 preg_replace_callback() 作为内部逻辑):

$string = "This is the paragraph which also contains link http://example.com/document/EN010001-0001, now this is some text after the link";
$replacements = array("EN010001-0001" => "EN010003-0001");
$regex = '~/document/([-\w]+)~';
$string = preg_replace_callback($regex,
    function($match) use ($replacements) {
        return $replacements[$match[1]];
    },
$string);
echo $string;

参见a demo on regex101.com。显然,您需要检查 match/key 是否真的在 $replacements 数组中。

您可以使用回顾:

$str = preg_replace('~(?<=http://example\.com/document/)[-\w]+~', 'EN010003-0001', $string);
//=> This is the paragraph which also contains link http://example.com/document/EN010003-0001, now this is some text after the link

另一种选择是使用\K(匹配重置):

$str = preg_replace('~http://example\.com/document/\K[-\w]+~', 'EN010003-0001', $string);