PHP regex combined with base64_encode()

Hi
In a text file which I open suing PHP, I want to change all occerences of:
username="some text here"
to such:
username="base64_encode(same text above)"
I'd like to use regular expressions for finding and replacing the strings.
Please guide
Huji
LVL 14
hujiAsked:
Who is Participating?
 
star_trekCommented:
oops mistake again, the corrected one

preg_replace_callback('/username="(\w+)"/',"matches",$input);

function matches($match) {
       return 'username="'.base64_encode($match[1])."'";
}
0
 
star_trekCommented:
can you explain of what exactly you want? Do you want to replace base64_encoded strings?
0
 
star_trekCommented:
make sure you have writable permissions to the output file/path($output_file).

In PHP 5
$input_file = "<inp-file>";
$output_file = "<out-file_with_path>";
file_put_contents($output_file,preg_replace("/username=(.*)/","username=".base64_encode('\1'),file_get_contents($input_file)));

IN PHP < 5
$input_file = "<inp-file>";
$output_file = "<out-file_with_path>";
$buff = preg_replace("/username=(.*)/","username=".base64_encode('\1'),file_get_contents($input_file));
$file = fopen("$output_file","w");
fwrite($file,$buff);
fclose($file);
0
 
hujiAuthor Commented:
It is not returing what I want.
Look at this piece of code:

<?
$input = 'username="abs"  text  <br> username="sdsdf"   text2';
echo preg_replace('/username=\"(.*?)\"/','username="'.base64_encode('\1').'"',$input);
?>

What it reutrns is this:

username="XDE=" text
username="XDE=" text2

XDE= is the base64_encode of the string '\1' and not the matched string.

What I expected was this:

username="YWJz" text
username="c2RzZGY=" text2

0
 
star_trekCommented:
I didn't reliaze you have two usernames on the same lines, any way you have to use preg_replace_callback, match is the function
preg_replace('/username="(\w+)"/',"matches",$input);

function matches($match) {
       return 'username="'.base64_encode($match[1])."'";
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.