php - 正则表达式:替换给定市场后出现的未知次数

标签 php regex preg-replace

我正在尝试找出一种方法,将 html 文件中 href 标记的 GET 部分中的 / 替换为 - ,如下所示:

blah blah <a href="aaaaa/aaaaa/aaaaa/?q=43/23"> blah blah <a
href="aaaaa/aaaaa/aaaaa/?q=43/11/1"> blah blah blah

所以基本上我希望使两个 URL 分别以 ?q=43-23?q=43-11-1 结尾。

如何使用 preg_replace 执行此操作?我显然可以通过

43/23 变为 43-23
/(\?.+?)\/(.+?)$/is

我可以将 43/11/1 变为 43-11-1

/(\?.+?)\/(.+?)\/(.+?)$/is

但是考虑到 后面可能有无限数量的斜杠,我该如何在单个正则表达式中执行此操作?。有什么建议或有人可以指出我正确的方向吗?

最佳答案

我认为这对您的内容来说可能很容易;

print preg_replace_callback('~\?q=([^&"]*)~', function($m) {
    return '?q='. str_replace('/', '-', $m[1]);
}, $s);
// for PHP < 5.3.0
print preg_replace_callback('~\?q=([^&"]*)~', create_function(
    '$m', 'return "?q=". str_replace("/", "-", $m[1]);'
), $s);

输出;

blah blah <a href="aaaaa/aaaaa/aaaaa/?q=43-23"> blah blah <a
href="aaaaa/aaaaa/aaaaa/?q=43-11-1"> blah blah blah
blah blah  blah blah  blah blah blah

关于php - 正则表达式:替换给定市场后出现的未知次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14946509/

相关文章:

php - php无法连接数据库?

php - preg_replace() 模式删除 php 中的括号和内容

php - 使用 preg_replace 更改字符串名称删除 espace 重音和点,但允许点扩展

php - 删除换行符和空格

PHP 数据库链接不起作用

php - 虚拟 PHP 表单

regex - 从一系列输入生成正则表达式

regex - 正则表达式 : Match a string that contains no more than three consecutive Bs (without using negative lookahead)

Javascript 简码解析

php - 使用 PHP 和 PDO 登录用户时遇到问题