dpv21589 2011-11-28 16:07
浏览 36
已采纳

PHP正则表达式替换链接

I have this replace regex (it's taken from the phpbb source code).

$match = array(
                '#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="(.*?)" target\=\"_blank\">.*?</a><!\-\- \1 \-\->#',
                '#<!\-\- .*? \-\->#s',
                '#<.*?>#s',
            );
$replace = array( '\2',  '', '');

$message = preg_replace($match, $replace, $message);

If I run it through a message like this

asdfafdsfdfdsfds
<!-- m --><a class="postlink" href="http://website.com/link-is-looooooong.txt">http://website.com/link ... oooong.txt</a><!-- m -->
asdfafdsfdfdsfds4324

It returns this

asdfafdsfdfdsfds
http://website.com/link ... oooong.txt
asdfafdsfdfdsfds4324

However I would like to make it into a replace function. So I can replace the link title in a block by providing the href.

I want to provide the url, new url and new title. So I can run a regex with these variables.

$url = 'http://website.com/link-is-looooooong.txt';
$new_title = 'hello';
$new_url = 'http://otherwebsite.com/';

And it would return the same raw message but with the link changed.

<!-- m --><a class="postlink" href="http://otherwebsite.com/">hello</a><!-- m -->

I've tried tweaking it into something like this but I can't get it right. I don't know how to build up the matched result so it has the same format after replacing.

$message = preg_replace('#<!\-\- ([mw]) \-\-><a (?:class="[\w-]+" )?href="'.preg_quote($url).'" target\=\"_blank\">(.*?)</a><!\-\- \1 \-\->#', $replace, $message);
  • 写回答

2条回答 默认 最新

  • doudouba4520 2011-11-28 16:41
    关注

    You need to catch the other parts in groups as well and then use them in the replacement. try something like this:

    $replace = '\1http://otherwebsite.com/\3hello\4';
    $reg = '#(<!-- ([mw]) --><a (?:class="[\w-]+" )?href=")'.preg_quote($url).'("(?: target="_blank")?>).*?(</a><!-- \2 -->)#';
    $message = preg_replace($reg, $replace, $message);
    

    See here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么