问题
I have an url which contains various POST-DATA in it And an image file at last.
My example link is : http://website-link.com/?page=gf_signature&signature=565dbca63791e5.87676354.png
I want to seperate the 565dbca63791e5.87676354.png from the url and seperate the extension (.png) from it.
I have tried this:
<?php
$images = array();
$imagesNew = array();
$imgUrls = array(
'ptSignature' => 'http://website-link.com/?page=gf_signature&signature=5668695879dc84.35037895.png',
'pSignature' => 'http://website-link.com/?page=gf_signature&signature=5668694f80aa55.79055562.png',
'witness1Signature' => 'http://website-link.com/?page=gf_signature&signature=5668695875c6e5.03917128.png',
'witness2Signature' => 'http://website-link.com/?page=gf_signature&signature=5668695879dc84.35037895.png',
)
function make_without_ext($str)
{
$regex = "/signature=(?<signature>[^&]+)/";
preg_match($regex, $str, $matches);
$signature = $matches["signature"];
$ext = substr(strrchr($signature, '.'), 1);
$without_extension = basename($signature, '.png');
return $without_extension;
}
foreach ($imgUrls as $imgUrl) {
$imgWithoutExt = make_without_ext($imgUrl);
array_push($images, $imgWithoutExt);
}
foreach ($images as $image) {
$content = file_get_contents($image);
$data = base64_encode($content);
array_push($imagesNew, $data)
}
print '<pre>';
print_r ($imagesNew);
print '<pre>';
But it shows syntax error, unexpected 'function' (T_FUNCTION)
回答1:
What I do for things like this is use PHP's explode function. Using your code, I would do something like this:
$str_parts = explode('.', $str);
$extension = array_pop($str_parts);
Note that this assumes you have a . in your string! Then you can just return your original string without this extension using substr or something. If signature is always the last parameter in your url, you could use the same technique to grab it if you wanted to although there are probably better ways to do that like using parse_url.
better working example
<?php
$url = "http://website-link.com/?page=gf_signature&signature=565dbca63791e5.87676354.png";
// to keep query only
$a = explode('&', parse_url($url, PHP_URL_QUERY));
$count = 0;
// looping parameters
foreach($a as $as => $that){
if(preg_match('|signature=|', $a[$count]) != false){
// this is like, if this string is contained in this string do that
$b = trim($a[$count], 'signature='); // to remove the part we dont want
$b = trim($b, '.png'); // again
echo $b; // voilà!
}
$count++;
}
?>
I must confess this foreach($a as $as => $that){ is kind of me trolling on a loop..
来源:https://stackoverflow.com/questions/34235369/retriving-only-file-name-without-extension-but-function-error