【发布时间】:2019-06-23 13:30:27
【问题描述】:
我有一个 html 文件,其中包含一些数据,包括一些 url。
仅在这些网址上,我想用空格替换 _ 字符(通过 php 文件)。
所以一个这样的网址:
</p><p><a rel="nofollow" class="external text" href="http://10.20.0.30:1234/index.php/this_is_an_example.html">How_to_sample.</a>
会变成
</p><p><a rel="nofollow" class="external text" href="http://10.20.0.30:1234/index.php/this is an example.html">How_to_sample.</a>
这不会影响不在网址上的_。
我认为这可能通过 preg_replace 实现,但我不知道如何进行。
以下代码不正确,因为它替换了每个 _ 而不仅仅是 url 中的那个。
$content2 = preg_replace('/[_]/', ' ', $content);
谢谢。
编辑:
感谢preg_replace_callback 的建议,这正是我想要的。
// search pattern
$pattern = '/href="http:\/\/10.20.0.30:1234\/index.php\/(.*?).html">/s';
// the function call
$content2 = preg_replace_callback($pattern, 'callback', $content);
// the callback function
function callback ($m) {
print_r($m);
$url = str_replace("_", " ", $m[1]);
return 'href="http://10.20.0.30:1234/index.php/'.$url.'.html">';
}
【问题讨论】:
-
使用
preg_replace_callback匹配网址,然后在回调中将_s 替换为str_replace(不要对静态字符串使用正则表达式...) . -
我在您的示例数据中看不到任何不合格的下划线。我的意思是,看起来您可以安全地替换所有下划线。请更新您的意见,让我代表您的情况。
-
preg_replace_callback 是我正在寻找的!谢谢。
-
答案不应作为对问题的编辑发布。这不是问答的运作方式。
-
是的,你是对的,但我无法正确发布答案。我有一条警告消息说我没有权限。
标签: php regex url preg-replace