替换文件路径字符串中间的目录

发布于 2024-09-18 02:32:36 字数 209 浏览 3 评论 0原文

$string = 'http://example.com/category/1/news/2134/'; // '1' is dynamic

如何将1更改为我想要的任何数字?

无法调用字符串的一部分,它只是一个类似文本的变量。

可以使用一些真正的正则表达式来完成。

$string = 'http://example.com/category/1/news/2134/'; // '1' is dynamic

How can I change 1 to any number I want?

Can't call parts of the string, its just a text-like variable.

It can be done with some true regex.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

七禾 2024-09-25 02:34:20

如果没有更多信息,我对您问题的最佳猜测是:

<?php
$string = 'http://site.com/category/' . $yourNumberHere . '/news/2134/';
?>

Without more information, my best guess at your problem is :

<?php
$string = 'http://site.com/category/' . $yourNumberHere . '/news/2134/';
?>
杀お生予夺 2024-09-25 02:34:06
$array = explode('/',$string);
$array[4] = '666';
$string = implode('/',$array);

[编辑]
@People downvoting,这种方法似乎有什么问题?

$array = explode('/',$string);
$array[4] = '666';
$string = implode('/',$array);

[edit]
@People downvoting, what seems to be the problem with this approach?

始终不够 2024-09-25 02:33:49
$string = preg_replace('~(?<=category/)[0-9]+(?=/news)~', '56', $string);

这会将数字替换为 56。

此方法使用带有 断言。

$string = preg_replace('~(?<=category/)[0-9]+(?=/news)~', '56', $string);

This replaces the number by 56.

This approach uses a regex with assertions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文