【问题标题】:php how to do base64encode while doing preg_replacephp在做preg_replace时如何做base64encode
【发布时间】:2015-03-30 07:30:48
【问题描述】:

我正在使用preg_replace 查找BBCODE 并将其替换为HTML 代码, 但是在这样做的时候,我需要base64encode url,我该怎么做?

我正在像这样使用preg_replace

<?php
$bbcode = array('#\[url=(.+)](.+)\[/url\]#Usi');

$html = array('<a href="$1">$2</a>');

$text = preg_replace($bbcode, $html,$text);

我怎样才能base64encodehref 值,即$1

我试过了:

$html = array('<a href="/url/'.base64_encode('{$1}').'/">$2</a>');

但它的编码是{$1},而不是实际的链接。

【问题讨论】:

  • 你试过base64_encode($1)吗? $html = array('$2');
  • @WahyuKodar 仍然无法正常工作,谢谢

标签: php base64 preg-replace encode


【解决方案1】:

您可以使用preg_replace_callback() 函数代替preg_replace

<?php

$text = array('[url=www.example.com]test[/url]');
$regex = '#\[url=(.+)](.+)\[/url\]#Usi';

$result = preg_replace_callback($regex, function($matches) {
    return '<a href="/url/'.base64_encode($matches[1]).'">'.$matches[2].'</a>';
}, $text);

它接受一个函数作为第二个参数。此函数从您的正则表达式中传递一个匹配数组,并期望返回整个替换字符串。

【讨论】:

    【解决方案2】:

    我猜你不能用preg_replace 来做,相反,你必须使用preg_match_all 并循环输入结果:

    $bbcode = array('#\[url=(.+)](.+)\[/url\]#Usi');
    $html = array('<a href="$1">$2</a>');
    $out = array();
    $text = preg_matc_all($text, $bbcode, $out, PREG_SET_ORDER);
    
    for ($i = 0; $i < count($out); $i++) {
       // $out[$i][0] should be the html matched fragment
       // $out[$i][1] should be your url
       // $out[$i][2] should be the anchor text
    
       // fills the $html replace var
       $replace = str_replace(
              array('$1','$2'), 
              array(base64_encode($out[$i][1]), $out[$i][2]), 
              $html);
    
       // replace the full string in your input text
       $text = str_replace($out[$i][0], $replace, $text);
    }
    

    【讨论】:

      猜你喜欢
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 2012-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-01
      • 2011-02-27
      相关资源
      最近更新 更多