Search code examples
phpbase64preg-replaceencode

php how to do base64encode while doing preg_replace


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.


Solution

  • 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.