php how to do base64encode while doing preg_replac

2019-06-10 08:40发布

问题:

I am using preg_replace to find BBCODE and replace it with HTML code, but while doing that, I need to base64encode the url, how can I do that ?

I am using preg_replace like this:

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

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

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

How can I base64encode the href value i.e. $1 ?

I tried doing:

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

but its encoding the {$1} and not the actual link.

回答1:

You can use preg_replace_callback() function instead of 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);

It takes a function as the second argument. This function is passed an array of matches from your regular expression and is expected to return back the whole replacement string.

TEST



回答2:

I guess you can't do it with preg_replace, instead, you have to use preg_match_all and loop in results:

$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);
}