【发布时间】:2017-06-12 10:31:04
【问题描述】:
我正在尝试替换 url 路径中的一个单词。
F.e. host.com/path/to/find 应该变成 host.com/path/to/count。
但我显然没有让这个工作。
我试图得到这个组:(?:/count|/find)? 在字符串的末尾
所有在它前面的都用$1/count替换它。
但总是当我尝试在 (?:/count|/find)? 之前获取部分时,我把它搞砸了。
这是一个测试:
编辑:所有键都代表测试(源)url。所有的值都代表预期的结果。
因此,如果路径上没有“/count”,则应该添加它。
如果末尾有“/count”,则无事可做。
如果路径末尾有“/find”,则应更改为“/count”。
如果 url 中有工作的“count”somewhere(如“countleaveMeAlone”),则不应更改(ofc)。
$urls = [
'http://foo-bar.host.com/entity/to' => 'http://foo-bar.host.com/entity/to/count',
'http://foo-bar.host.com/entity/to/' => 'http://foo-bar.host.com/entity/to/count',
'http://foo-bar.host.com/entity/to/find' => 'http://foo-bar.host.com/entity/to/count',
'http://foo-bar.host.com/entity/to/find/' => 'http://foo-bar.host.com/entity/to/count/',
'http://foo-bar.host.com/entity/to/find?some=foo' => 'http://foo-bar.host.com/entity/to/count?some=foo',
'http://foo-bar.host.com/entity/to/find/?foo=some' => 'http://foo-bar.host.com/entity/to/count/?foo=some',
'http://foo-bar.host.com/entity/to/count' => 'http://foo-bar.host.com/entity/to/count',
'http://foo-bar.host.com/entity/to/count/' => 'http://foo-bar.host.com/entity/to/count/',
'http://foo-bar.host.com/entity/to/count?some=foo' => 'http://foo-bar.host.com/entity/to/count?some=foo',
'http://foo-bar.host.com/entity/to/count/?foo=some' => 'http://foo-bar.host.com/entity/to/count/?foo=some',
'http://foo-bar.host.com/entity/toleaveMeAlone' => 'http://foo-bar.host.com/entity/toleaveMeAlone',
'http://foo-bar.host.com/entity/to/leaveMeAlone' => 'http://foo-bar.host.com/entity/to/leaveMeAlone',
'http://foo-bar.host.com/entity/to/countleaveMeAlone' => 'http://foo-bar.host.com/entity/to/countleaveMeAlone',
'http://foo-bar.host.com/entity/to/count/leaveMeAlone' => 'http://foo-bar.host.com/entity/to/count/leaveMeAlone',
'http://foo-bar.host.com/entity/to/countleaveMeAlone?some=foo' => 'http://foo-bar.host.com/entity/to/countleaveMeAlone?some=foo',
'http://foo-bar.host.com/entity/to/count/leaveMeAlone?foo=some' => 'http://foo-bar.host.com/entity/to/count/leaveMeAlone?foo=some',
];
$format = "%-70s%-70s%s\r\n";
echo sprintf($format, 'TEST', 'EXPECT', 'SUCCESS');
foreach ($urls as $url => $expect) {
$tmp = explode('?', $url);
$url = rtrim($tmp[0], '/');
$query = isset($tmp[1])
? $tmp[1]
: '';
/**
* Pattern
* /
* \A --start string
* (.*) --get all before
* (?:/count|/find)? --get optional "/find" or "/count"
* \z --end string
* /
*/
$url = preg_replace(
"#\A(.*)(?:/count|/find)?\z#",
'$1/count',
$url
);
$url .= strlen($query)
? '?' . $query
: '';
echo sprintf($format, $url, $expect, var_export($url === $expect, true));
}
非常感谢任何帮助
【问题讨论】:
-
所以你想在 URL 中用 'count' 替换 'find' 吗?在我回答之前想澄清一下。
-
“find”可以在 url 中出现多次还是在路径中出现一次?
-
$url = preg_replace("#\A(.*)(?:/count|/find)?\z#", '$1/count', $url);将其替换为 $url = preg_replace( "#\A(.*)(?:/count|/find)?\z#", "$1/count", $url );
-
为什么不使用 str_replace?如果这只是我们正在谈论的静态替换
-
你说得对@Andreas,str_replace也可以用,如果你需要
preg_split,$url = preg_replace('/\/find/', '/count');