Question
PHP: run a function during preg_replace
This is an ongoing issue (sadly unsolved), if you're bored
enough you can
see my other posts.
The code I have so far (thanks to one and all), successfully creates
hyperlinks that target the right files, have the right 'title', etc.
However, the getFileSize function refuses to work within the preg_replace.
Seems to me that I can't properly send the $1 variable to the getFileSize
function; the $strfilename always just shows up as $1, but really it should
be a file name, as it is within the hyperlink section. Most boring.
So, does anyone know how to trigger the getFileSize by sending $1 as a
string rather than just as a variable name '$1'?
When called separately the function getFileSize works, so the issue really
is the getFileSize('$1') section.
<?php function changeMe($str){
$pattern = "/\{([^:]*):([^\}]*)\}/";
preg_match($pattern,$str,$matches);
$file = $matches[2];
$pattern = "/\{link:([^\}]*)\}/";
return preg_replace($pattern,'<a href="docs/$1" title="click to open $1"
target="_blank">'.getFileSize('$1').'</a>',$str);}
?>
<?
function getFileSize($strfilename){
echo $strfilename.'<br />'; //returns $1 but should really return the file
name
$pathname='docs/';
$fullname=$pathname.$strfilename;
if (file_exists($fullname)){
$strsize = human(filesize($fullname));
return($strfilename.' : '.$strsize);
} else {
return("no file found");
}
return;
}
function human($size){
for($si = 0; $size >= 1024; $size /= 1024, $si++);
return round($size, 1).substr(' kMG', $si, 1);}
?>
see my other posts.
The code I have so far (thanks to one and all), successfully creates
hyperlinks that target the right files, have the right 'title', etc.
However, the getFileSize function refuses to work within the preg_replace.
Seems to me that I can't properly send the $1 variable to the getFileSize
function; the $strfilename always just shows up as $1, but really it should
be a file name, as it is within the hyperlink section. Most boring.
So, does anyone know how to trigger the getFileSize by sending $1 as a
string rather than just as a variable name '$1'?
When called separately the function getFileSize works, so the issue really
is the getFileSize('$1') section.
<?php function changeMe($str){
$pattern = "/\{([^:]*):([^\}]*)\}/";
preg_match($pattern,$str,$matches);
$file = $matches[2];
$pattern = "/\{link:([^\}]*)\}/";
return preg_replace($pattern,'<a href="docs/$1" title="click to open $1"
target="_blank">'.getFileSize('$1').'</a>',$str);}
?>
<?
function getFileSize($strfilename){
echo $strfilename.'<br />'; //returns $1 but should really return the file
name
$pathname='docs/';
$fullname=$pathname.$strfilename;
if (file_exists($fullname)){
$strsize = human(filesize($fullname));
return($strfilename.' : '.$strsize);
} else {
return("no file found");
}
return;
}
function human($size){
for($si = 0; $size >= 1024; $size /= 1024, $si++);
return round($size, 1).substr(' kMG', $si, 1);}
?>
