Code breaks when using later version of PHP
I have the following code which breaks when I upgrade from PHP v5.2.17 --> v5.3.5 and I can't figure out what it is. Does anyone have a clue as to what could be wrong? Thanks.
<?php
setlocale(LC_ALL, 'en_US.UTF8');
$goto = $_POST['location'];
function toAscii($str, $replace=array(), $delimiter='-') {
if( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
return $clean;
}
?>
There are no errors of any sort and I looked over my cms logs and there is nothing unusual. I did setup a simple test and here is what happens:
<?php
$goto = $_POST['location'];
function toAscii($str, $replace=array(), $delimiter='-') {
if( !empty($replace) ) {
$str = str_replace((array) $replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|开发者_如何学Python+ -]+/", $delimiter, $clean);
return $clean;
}
?>
Output is: <?echo toAscii($goto);?>
Output is: <?echo $goto;?>
When I output the raw form data it works great and when I output the toAscii($goto)
data it returns nothing.
You have not added an error message to your question, but as the code uses only one non-standard function, namely iconv
, it's hightly likely that you haven't installed/enabled the iconv extension.
To solve the problem, enable the needed extension and the code should work as you know it from the other PHP configuration.
If the extension is available and enabled (which should be the case with PHP 5.3) from the top of my head, then you should add more information to your question what's actually breaking. What is not working as intended?
To troubleshoot, above your code place:
error_reporting(-1);
ini_set('display_errors', 1);
This will take care that errors and warnings are directly visible.
To continue trouble shooting, let's take care inside the routine that is not properly working. Exemplary I've added a check for the return value of iconv
, the same can be applied on any kind of variable (testing if a variable contains what should be expected) or function return values:
function toAscii($str, $replace=array(), $delimiter='-') {
if( !empty($replace) ) {
# NOTE: no need to cast to array. It's either array or string, both work
$str = str_replace($replace, ' ', $str);
}
# NOTE: inconv will return FALSE on error. Checking this now.
$result = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
if (FALSE === $result) {
throw new Exception(sprintf('Iconv failed on "%s".', $str));
} else {
$clean = $result;
}
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
return $clean;
}
精彩评论