PrisonPants PrisonPants - 2 months ago 12
PHP Question

Encode contents between Two Special Strings

All i want is to Get contents between two strings like the following line:

$content = '81Lhello82R 81Lmy82R 81Lwife82R';


I wish to get all contents between
81L
and
82R
, then encode them to Base64 automatically by Preg_match i think, i've done some ways to do it but didn't get what was expected!

Base Form:

81Lhello82R 81Lmy82R 81Lwife82R


Output:

81LaGVsbG8=82R 81LbXk=82R 81Ld2lmZQ==82R

Answer

Hard rules:

$leftMask = '81L';
$rightMask = '82R';
$content = '81Lhello82R 81Lmy82R 81Lwife82R';
preg_match_all('#'.$leftMask.'(.*)'.$rightMask.'#U',$content, $out);
$output = [];
foreach($out[1] as $val){
   $output[] = $leftMask.base64_encode($val).$rightMask;
}
$result = str_replace($out[0], $output, $content);

RegExp rules

$leftMask = '\d{2}L';
$rightMask = '\d{2}R';
$content = '81Lhello82R 81Lmy82R 81Lwife82R';
preg_match_all('#('.$leftMask.')(.*)('.$rightMask.')#U',$content, $out);;
$output = [];
foreach($out[2] as $key=>$val){
   $output[] = $out[1][$key].base64_encode($val).$out[3][$key];
}
$result = str_replace($out[0], $output, $content);