【问题标题】:Alter all occurence of href values with php使用 php 更改所有出现的 href 值
【发布时间】:2016-02-12 18:16:00
【问题描述】:

我想在将 href 标记的所有值提交到数据库之前更改它们。

假设我有一个包含一些锚标记的段落,我想更改所有锚标记的值。

我的目标是对 url 进行 base64 编码,然后在 url 上附加一个前缀 如果一个网址是

http://google.com

在提交之前想把它改成 http://exmaple.com/visit/base64encodeedurl

【问题讨论】:

  • 你能贴一些你的代码吗??
  • @Drudge 我还没有研究它。但我找到了替换所有网址的代码$newurl = "http://myotherexample.com"; $pattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/"; $newstring = preg_replace($pattern,$newurl,$string);

标签: php regex preg-replace


【解决方案1】:

你可以使用preg_replace_callback函数和base64_encode函数

$string = 'Your string to save with http://goo.gl urls ...';
$fixedString = preg_replace_callback(
    '#[-a-zA-Z0-9@:%_\+.~\#?&//=]{2,256}\.[a-z]{2,18}\b(\/[-a-zA-Z0-9@:%_\+.~\#?&//=]*)?#si',
    function($matches) {
        return 'http://exmaple.com/visit/' . base64_encode($matches[0]); 
    },
    $string
);

这里是一个活生生的例子https://3v4l.org/TUktY

【讨论】:

  • 我收到此错误PHP Catchable fatal error: Object of class Closure could not be converted to string in
  • 抱歉我写的是preg_replace而不是preg_replace_callback
  • 固定为[a-z]{2,18} 感谢您的报告 :)
猜你喜欢
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多