PHP Function running locally but not within a loop - php

I have this function and statements running fine in my page:
$name = "JÜRGEN RÜDIGER HERMANN";
function nameReplace($name)
{
$name = str_replace("Ñ", "N", $name);
$name = str_replace("Ü", "U", $name);
$name = str_replace("Ç", "C", $name);
$name = str_replace("Á", "A", $name);
$name = str_replace("É", "E", $name);
return $name;
}
$name = nameReplace($name);
echo "This is the name!" . $name . "<br>";
$orename = "ÑÜÇÁÉ";
$orename = nameReplace($orename);
echo "Forename test: " . $orename . "<br>";
$astname = "ÁÉÑÜÇ";
$astname = nameReplace($astname);
echo "Lastname test: " . $astname . "<br>";
Everything about works fine, the characters are changed to acceptable characters for upload into a progress DB. But later in the page I'm looping through data and taking strings from a parsed HTML file:
$familyname = nameReplace($familyname);
The above familyname nameReplace() fails. If I echo out just family name it echoes out the string. If I echo out nameReplace($familyname) it returns blank or false.
Any ideas? Do functions have a specific scope?
Thanks,
Stephen.
Below is the code for the loop as requested:
for($i=1;$i<41;$i++)
{
$textfile = 'interpol_create' . $i. '_' . $date . '.txt';
$myfile = fopen($textfile, "r") or die("Unable to open file!");
if($myfile)
{
#read through the file line by line
while (($buffer = fgets($myfile, 4096)) !== false)
{
$linenumber++;
if( (strstr($buffer, '<span')) && (strstr($buffer, 'titre')))
{
$buffer = str_replace('<br />', '|', $buffer);
#echo $buffer . '<br>';
$result = explode('|', $buffer);
#family name variable
$familyname = $result[0];
$familyname = str_replace('<span class="titre">', '', $familyname);
$familyname = trim($familyname);
$familyname = nameReplace($familyname);
#first name variable
$forename = $result[1];
$forename = nameReplace($forename);
if(strstr($forename, "RGEN"))
{
echo "Forename is ".nameReplace((string)$forename)."<br>";
$newVar = "JÜRGEN RÜDIGER";
$newVar = nameReplace($newVar) . "<br>";
echo "New variable = " . $newVar . "<br>";
}
$forename = str_replace("</span>", "", $forename);
$forename = trim($forename);
#echo ($namecounter + 1) . ' | ';
#echo 'Family name : ' . $familyname . ' | Forename is : ' . $forename . '<br>';
$update_full_file .= $forename . " " . $familyname;
$firstnames[$namecounter] = $forename;
$lastnames[$namecounter] = $familyname;
}#end of if strstr $buffer
if( (strstr($buffer, 'Age today :')) && (strstr($buffer, '<br')))
{
$buffer = str_replace('<br />', '', $buffer);
$buffer = str_replace('Age today :', '', $buffer);
$agetoday = $buffer;
$agetoday = str_replace("<br/>", "", $agetoday);
$agetoday = trim($agetoday);
#echo 'Age Today : ' . $agetoday . '<br>';
$ages[$namecounter] = $agetoday;
$update_full_file .= ",," . $agetoday;
$nextlinenumber = $linenumber + 2;
$nationalitylinenumbers[$namecounter] = $nextlinenumber;
#echo $nationcounter . " " . $nextlinenumber . '<br>';
}
if( (strstr($buffer, 'Nationality :')) )
{
#$buffer = str_replace('<br />', '', $buffer);
#$buffer = str_replace('Age today :', '', $buffer);
#echo 'Nationality : ' . $buffer . '<br>';
#echo 'Line number : ' . $linenumber . '<br>';
}
if( in_array($linenumber, $nationalitylinenumbers) )
{
#echo $nationcounter . $buffer . '<br>';
#$nationcounter++;
}
###does the current linenumber appear in the array $nationalitylinenumbers?###
if( in_array($linenumber, $nationalitylinenumbers) )
{
$nation = $buffer;
$nation = str_replace("<br/>", "", $nation);
$nation = str_replace("</div>", "", $nation);
$nation = str_replace(" ", "", $nation);
#$nation = str_replace(",", "", $nation);
$nation = str_replace('<divclass="sep">', 'No Country', $nation);
$nation = trim($nation);
if(strstr($nation, ','))
{
#echo 'Create a duplicate entry';
$nations = explode(',', $nation);
$nation = $nations[0];
$nation = trim($nation);
$duplicateNation = $nations[1];
$duplicates[$duplicate_counter] .= $forename . " " .$familyname . ",," . $agetoday . ",,,,,". trim($duplicateNation) .",,,,,\n";
$duplicate_counter++;
}
#$nation = countryMappings($nation);
###check to see if entry has 2 countries###
#echo $nationcounter . $nation . '<br>';
$nationcounter++;
$update_full_file .= ",,,,," .$nation. ",,,,,\n";
$nationalitys[$namecounter] = $nation;
#echo $buffer.'<br>';
$namecounter++;
}
}#end of while buffer = fgets
}#end of if myfile
}

I managed to fix this!
The issue was I was translating the wrong data. I parsed in the 'Ü' character and was using:
$name = str_replace("Ü", "U", $name);
I exported the data to a text file and found that the character is actually exporting as Ãœ instead of Ü. I amended my function to be as below and it now works:
$name = str_replace("Ü", "U", $name);
Thanks again to all who responded, all the tips were very helpful.

Related

clean imported xls file with php

When I import XLS files, I would like to avoid the import of empty rows. I tried with several codes without success. Can anyone help me?
This is the code:
require('xls/php-excel-reader/excel_reader2.php');
require('xls/SpreadsheetReader.php');
require_once '_inc/_db.php';
$r = rand();
$mimes = ['application/vnd.ms-excel', 'text/xls', 'text/xlsx', 'application/vnd.oasis.opendocument.spreadsheet'];
if (in_array($_FILES["file"]["type"], $mimes)) {
$uploadFilePath = 'storage/' . basename($_FILES['file']['name']);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath);
rename($uploadFilePath, "storage/" . $r . ".xls");
$uploadFilePath = "storage/" . $r . ".xls";
$Reader = new SpreadsheetReader($uploadFilePath);
$totalSheet = count($Reader->sheets());
$tot = 0;
/* For Loop for all sheets */
for ($i = 0; $i < $totalSheet; $i++) {
$Reader->ChangeSheet($i);
$tots = $totalSheet;
foreach ($Reader as $Row) {
$tot++;
$nrcontenitore = isset($Row[0]) ? $Row[0] : '';
$nrcontenitore = str_replace(".", "", $nrcontenitore);
$nrcontenitore = str_replace("-", "", $nrcontenitore);
$nrcontenitore = str_replace("_", "", $nrcontenitore);
$nrcontenitore = str_replace("/", "", $nrcontenitore);
$nrcontenitore = str_replace("\'", "", $nrcontenitore);
$nrcontenitore = preg_replace('/\s+/', '', $nrcontenitore);
$nrcontenitore = isset($Row[0]) ? $Row[0] : '';
$data = isset($Row[1]) ? $Row[1] : '';
$doc .= formatcontainernr(strtoupper($nrcontenitore)) . " | " . date("d/m/Y", strtotime($data)) . "\n";
$docarr .= formatcontainernr(strtoupper($nrcontenitore)) . " | " . date("d/m/Y", strtotime($data)) . "#\n";
}
}
}
I would like to import a XLS file with no empty rows.
try to add a checking if the row is empty
foreach ($reader as $row) {
if($row == null){
continue;
}
}

PHP variable as hyperlink

I'm trying to set the php variables linked to one of my page in the folder, index.html. However, I am getting an error of Name&lang=en"> Any help?
if (isset($result_array)) {
foreach ($result_array as $result) {
$name = preg_replace("/" . $search . "/i", "<b class='high'>" . $search . "</b>", $result['Name']);
$url = '<a href="index.html">' . urlencode($result['Name']) . '&lang=en';
$out = str_replace('nameS', $name, $html);
$out = str_replace('urlS', $url, $out);
$_SESSION[$search] = $result['Name'];
echo($out);
}
}

I am unable to display the data in Address column in excel sheet

I need to display the complete address details in Address column, but I am displayed like this:
.
Can you please help me? How to solved the issue.
<?php $users = elgg_get_entities(array( 'type' => 'user', 'limit' => 9999)); $data = array(); foreach($users as $euser){
if($euser->banned == "no" && $euser->enabled == "yes") {
if(!$euser->ext_mod){
$user = new SsportalUser($euser);
$row = array();
$row['Address'] = $user->basic('address');
array_push($data, $row);
} } }function cleanData(&$str) {
$str = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '', $str);
$str = preg_replace('/\s/u', '', $str);
$str = preg_replace("/\r?\n/", "\\n", $str);
if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; } header("Content-Disposition: attachment;filename=active_users_list.xls");header("Content-Type: application/vnd.ms-excel"); $flag = false;foreach($data as $row) {if(!$flag) {
echo implode("\t", array_keys($row)) . "\r\n";
$flag = true;
}
array_walk($row, 'cleanData');
echo implode("\t",array_values($row))."\r\n";
}exit;

extract part of a string before and after a word

i need to extract and show some words before and after a query word, something like google search results, for example:
$str = "hi user! welcome to new php open source world, we are trying to learn you something!";
$query = "new php";
$result = "... welcome to new php open source ...";
i searched google an SO but didn't find a clear answer or maybe my php knowledge was not enough!
is there a workable and easy-to-use function to do this job?
function yourFuncName($str, $query, $numOfWordToAdd) {
list($before, $after) = explode($query, $str);
$before = rtrim($before);
$after = ltrim($after);
$beforeArray = array_reverse(explode(" ", $before));
$afterArray = explode(" ", $after);
$countBeforeArray = count($beforeArray);
$countAfterArray = count($afterArray);
$beforeString = "";
if($countBeforeArray < $numOfWordToAdd) {
$beforeString = implode(' ', $beforeArray);
}
else {
for($i = 0; $i < $numOfWordToAdd; $i++) {
$beforeString = $beforeArray[$i] . ' ' . $beforeString;
}
}
$afterString = "";
if($countAfterArray < $numOfWordToAdd) {
$afterString = implode(' ', $afterArray);
}
else {
for($i = 0; $i < $numOfWordToAdd; $i++) {
$afterString = $afterString . $afterArray[$i] . ' ';
}
}
$string = $beforeString . $query . ' ' . $afterString;
return $string;
}
Output is: user! welcome to new php open source world, ($numOfWordToAdd = 3)
Here is an working example I thing that it is clear what I did and how:
<?php
$str = "hi user! welcome to new php open source world, we are trying to learn you something!";
$query = "new php";
$expl = explode($query, $str);
// items on the left side of middle string
$expl_left = explode(" ", $expl[0]);
$left_cnt = count($expl_left);
$new_left = $expl_left[$left_cnt-3] . " " . $expl_left[$left_cnt-2];
// items on the right side of middle string
$expl_right = explode(" ", $expl[1]);
$new_right = $expl_right[1] . " " . $expl_right[2];
// new string formated
$new = "... " . $new_left . " " . $query . " " . $new_right . " ...";
print $new;
?>
If you have some questions feel free to ask...
$result = preg_replace('/(.+)?([^\s]+.{10}'.$query.'.{10}[^\s]+)(.+)?/', '... $2 ...', $str);
This will return the same result from the same string and query you gave. If the before or after length starts or ends (respectively) in the middle of a word, it will continue until it completes the word before it stops.
Assuming a "word" is any series of non-whitespace characters, the following will extract 3 words on either side of new php out of the string $subject, but accept less if necessary:
if (preg_match('/(?:\S+\s+){1,3}new php(?:\s+\S+){1,3}/', $subject, $regs)) {
$result = $regs[0];
}
Change the 3s to any number you like.
I used the following function with explode:
public static function returnSearch($query, $str, $wordcount) {
$explode = explode($query, $str);
$result = null;
//if explode count is one the query was not found
if (count($explode) == 1) {
$result = implode(' ', array_slice(str_word_count($explode[0], 2), -$wordcount, $wordcount)) . " ";
}
//if explode count is more than one the query was found at least one time
if (count($explode) > 1) {
//check for if the string begins with the query
if (!empty($explode[0])) {
$result = "..." . implode(' ', array_slice(str_word_count($explode[0], 2), -$wordcount, $wordcount)) . " ";
}
$result = $result . $query;
if (!empty($explode[1])) {
$result = $result . " " . implode(' ', array_slice(str_word_count($explode[1], 2), 0, $wordcount)) . "...";
}
}
//return result
return $result;
}
Corrected function from #Can Vural, it wont mess the phrase of the before match and its case insensitive, very usefull to dispaly in php search results:
function render_search_words($str, $query, $numOfWordToAdd) {
list($before, $after) = preg_split("/$query/i", $str);
$before = rtrim($before);
$after = ltrim($after);
$beforeArray = explode(" ", $before);
$afterArray = explode(" ", $after);
$countBeforeArray = count($beforeArray);
$countAfterArray = count($afterArray);
$beforeString = "";
if($countBeforeArray < $numOfWordToAdd) {
$beforeString = implode(' ', $beforeArray);
}
else {
for($i = 0; $i < $numOfWordToAdd; $i++) {
$beforeString = $beforeArray[$i] . ' ' . $beforeString;
}
}
$afterString = "";
if($countAfterArray < $numOfWordToAdd) {
$afterString = implode(' ', $afterArray);
}
else {
for($i = 0; $i < $numOfWordToAdd; $i++) {
$afterString = $afterString . $afterArray[$i] . ' ';
}
}
$string = '...'.$beforeString . ' <span>' . $query . '</span> ' . $afterString.'...';
return $string;
}

PHP For Each Loop? There has to be a better way

<?php
header("Content-type: text/plain");
$GLOBALS["db_name"] = "fggff_highscores";
$GLOBALS["table_name"] = "testing";
$GLOBALS["view_user"] = "fgfggg_players";
$GLOBALS["view_pass"] = "removed";
$username = strip_tags($_GET["player"]);
$fileContents = #file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=" . $username);
echo $fileContents;
if ($fileContents == FALSE) {
die("PLAYER NOT FOUND");
}
//$content = array();
$data = explode("\n", $fileContents);
/*
foreach ($data as $word) {
$index = $skills[$index];
$new_data = explode (",", $word);
$content[$index]["rank"] = $new_data[0];
$content[$index]["level"] = $new_data[1];
$content[$index]["experience"] = $new_data[2];
$index++;
}
*/
$stats0 = explode(",", $data[0]);
echo "\n";
echo "\n";
echo "Overall Rank: " .number_format($stats0[0]);
echo "\n";
echo "Total Level: " .number_format($stats0[1]);
echo "\n";
echo "Overall Total XP: " .number_format($stats0[2]);
$stats1 = explode(",", $data[1]);
echo "\n";
echo "\n";
echo "Attack Rank: " .number_format($stats1[0]);
echo "\n";
echo "Attack Level: " .number_format($stats1[1]);
echo "\n";
echo "Attack XP: " .number_format($stats1[2]);
$stats2 = explode(",", $data[2]);
echo "\n";
echo "\n";
echo "Defence Rank: " .number_format($stats2[0]);
echo "\n";
echo "Defence Level: " .number_format($stats2[1]);
echo "\n";
echo "Defence XP: " .number_format($stats2[2]);
?>
Example above should be working when ran you can use this player to see output -- .php?player=zezima
The output of each $data[0] is something like--------53,2496,1661657944
53-----------------------number_format($stats0[0])
2,496--------------------number_format($stats0[1])
1,661,657,944------------number_format($stats0[2])
--
Then I'm trying to break up each $data[] index into 3 pieces, the way I have it above works but I want to be able to do something like a for each loop to go through each $data[] indexes and break each up using explode(",", $data[0]); explode(",", $data[1]); explode(",", $data[2]); but it would have the index increment each time. What I need in the end is each value to be in a variable that I can use. Example:
$apple = number_format($stats0[0]);
echo $apple;
This is what I've tried something with:
$content = array();
foreach ($data as $word) {
$index = $skills[$index];
$new_data = explode (",", $word);
$content[$index]["rank"] = $new_data[0];
$content[$index]["level"] = $new_data[1];
$content[$index]["experience"] = $new_data[2];
$index++;
}
instead of repeating yourself again and again, create a function like this one:
function print($data, $i){
$stats0 = explode(",", $data[$i]);
echo "\n\nOverall Rank: " .number_format($stats0[0]) . "\n";
echo "Total Level: " .number_format($stats0[1]) . "\n";
echo "Overall Total XP: " .number_format($stats0[2]);
}
and call it in a loop.

Categories