Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何使用正则表达式替换字符串中出现的路径中的ID_Php_Regex_Preg Replace - Fatal编程技术网

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

Php 如何使用正则表达式替换字符串中出现的路径中的ID,php,regex,preg-replace,Php,Regex,Preg Replace,示例 $string = "This is the paragraph which also contains link http://example.com/document/EN010001-0001, now this is some text after the link"; 考虑到上面的例子,如果链接可以出现在字符串中的任何位置,我想用不同的ID替换这个EN010001-0001,例如EN010003-0001 我知道我们可以使用preg\u replace,有人能帮我们为这个场景提

示例

$string = "This is the paragraph which also contains link http://example.com/document/EN010001-0001, now this is some text after the link";
考虑到上面的例子,如果链接可以出现在字符串中的任何位置,我想用不同的ID替换这个
EN010001-0001
,例如
EN010003-0001

我知道我们可以使用
preg\u replace
,有人能帮我们为这个场景提供正确的正则表达式吗

编辑#1

链接<代码>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\u replace\u callback()
):


看。显然,您需要检查match/键是否真的在
$replacements
数组中。

您可以使用lookback:

$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

链接是否保证为http/s,或者是否允许相对路径?链接是静态的。请提供更多的输入字符串,目前,您甚至可以想出一些简单的方法,如
文档/([-\w]+)
,但这肯定不是您想要的。这很有效-很好,这会取代所有发生的事情吗?是的,它会取代所有发生的事情。请您推荐您认为学习reg表达式的最佳资源?
$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
$str = preg_replace('~http://example\.com/document/\K[-\w]+~', 'EN010003-0001', $string);