Right Now I Have:
$path2 = $file_list1;
$dir_handle2 = #opendir($path2) or die("Unable to open $path2");
while ($file2 = readdir($dir_handle2)) {
if($file2 == "." || $file2 == ".." || $file2 == "index.php" )
continue;
echo ''.$file2.'<br />';
}
closedir($dir_handle2);
echo '<br />';
When $file2 is returned, the last 4 characters in the string will always end in a number plus the file extension .txt, like this:
file_name_here1.txt
some_other-file10.txt
So my question is, how can I separate $file2 so it returns the string in two parts, $file_name and $call_number like this?:
echo 'File: '.$file_name.' Call: '.call_number.'<br />';
Returns:
File: file_name_here Call: 1
File: some_other-file Call: 10
instead of this:
echo ''.$file2.'<br />';
Returns:
file_name_here1.txt
some_other-file10.txt
Thanks....
I'm a big advocate of Regex but I decided to go slightly different here. Check it out:
$file = 'file_name_here19.txt';
$file_parts = pathinfo($file);
$name = $file_parts['filename'];
$call = '';
$char = substr($name, strlen($name) - 1);
while(ord($char) >= 48 && ord($char) <= 57) {
$call = $char . $call;
$name = substr($name, 0, strlen($name) - 1);
$char = substr($name, strlen($name) - 1);
}
echo 'Name: ' . $name . ' Call: ' . $call;
Use regular expressions:
preg_match("/^(.+)(\d+)(\..+)$/", $file2, $matches);
$file_name = $matches[1];
$call_number = $matches[2];
Try this, you need to use Regex to do this effectively
$filename = reset(explode(".", $file2))
preg_match("#(^[a-zA-Z\_\-]*)([\d]*)#", $filename, $matches);
$fullMatch = $matches[0];
$file = $matches[1];
$call = $matches[2];
echo "File: " . $file . " Call: " . $call;
Use pathinfo() function to cut off file extension.
Use preg_match() function to separate name from number.
3.
while (...) {
...
$filename; // some_other-file10.txt
$filename = pathinfo($filename, PATHINFO_FILENAME); // some_other-file10
preg_match('/^(?<name>.*?)(?<number>\d+)$/', $filename, $match);
$match['name']; // some_other-file
$match['number']; // 10
echo "File: {$match['name']} Call: {$match['number']}\n";
}
Related
I'm dealing with this php script, which when executed on the host gives a 500 error, apparently the line where the preg_match is is the one that contains the error...
this file is going to be executed as a cron to validate.
<?php
$encoded = wordwrap($encoded, 80, "\xa", true);
$license_file = $dir . "/modules/addons/Kayako/license.php";
if ($key != $sellKey) {
die("Invalid "license . php" file!");
}
function getWhmcsDomain() {
if (!empty($_SERVER["SERVER_NAME"])) {
return $_SERVER["SERVER_NAME"];
}
}
$license["checkdate"] = date("Ymd");
$keyName = $modleName . "_licensekey";
$dir = __DIR__;
$encoded = strrev($encoded);
$license["status"] = "Active";
$sellKey = "ModulesGarden_Kayako_54M02934WH301844E_HackbyRicRey";
$license["checktoken"] = $checkToken;
$key_data = WHMCS\Database\Capsule::table("tblconfiguration")->where("setting", "kayako_localkey")->first();
$license = array("licensekey" => $key, "validdomain" => getWhmcsDomain(), "validip" => getIp(), "validdirectory" => $dir . "/modules/addons/Kayako," . $dir . "/modules/addons," . $dir . "/modules/addons/Kayako," . $dir . "/modules/addons/Kayako," . $dir . "/modules/addons," . $dir . "," . $dir . "/modules");
$secret = "659c08a59bbb484f3b40591";
include_once "init.php";
function getIp() {
return isset($_SERVER["SERVER_ADDR"]) ? $_SERVER["SERVER_ADDR"] : $_SERVER["LOCAL_ADDR"];
}
if (!$key_data) {
WHMCS\Database\Capsule::table("tblconfiguration")->insert(array("setting" => "kayako_localkey", "value" => ''));
}
$checkToken = time() . md5(rand(1000000000, 0) . $key);
$modleName = "kayako";
$encoded = $encoded . md5($encoded . $secret);
$encoded = serialize($license);
preg_match("/kayako_licensekey\s?=\s?"([A - Za - z0 - 9_] +) "/", $content, $matches);
$encoded = md5($license["checkdate"] . $secret) . $encoded;
$key = $matches[1];
$encoded = base64_encode($encoded);
if (file_exists($license_file)) {
$content = file_get_contents($license_file);
} else {
echo "Please Upload "license . php" File Inside: " . $dir . "/modules/addons/Kayako/";
}
$content = '';
try {
WHMCS\Database\Capsule::table("tblconfiguration")->where("setting", "kayako_localkey")->update(array("value" => $encoded));
echo "Done!";
}
catch(\Throwable $e) {
echo "There is an issue, contact.";
} ?>
You have extra double quotes in the regular expression. You also have extra spaces inside the [] in the regexp. You can replace that character class with \w, which matches alphanumerics and underscore.
preg_match('/kayako_licensekey\s?=\s?(\w+)/', $content, $matches);
Another problem: You use a number of variables before you assign them:
$modleName
$checkToken
$key
$sellKey
$dir
Did you post the code out of order?
I need a PHP script to print customer names in a file. There's hundreds of names and addresses but I want to print only the names with a maximum of 15 letters.
<?php
$file = file_get_contents('data-cust.txt');
$keyword = 'name';
$str = substr($file, strpos($file, $keyword) + strlen($keyword), 15);
echo $str;
?>
I tried using the above but only printed one name. How do I make it print all names?
Thanks.
If the names are on their own line, something like this should work.
<?php
$file = file('data-cust.txt');
foreach($file as $line) {
$keyword = 'name';
$str = substr($line, strpos($line, $keyword) + strlen($keyword), 15);
echo $str;
}
You need to open the file and read it then extract the names.
$file = fopen("data-cust.txt", "r");
$keyword = 'name';
$str = array() ;
if ($file) {
while (($line = fgets($file )) !== false) {
$name = substr($line, strpos($line, $keyword) + strlen($line), 15);
echo $name ;
$str[] = $name ;
}
} else {
// error opening file
}
fclose($file );
print_r($str) ;
I have this function that checks for a filename. If it exists, it increments it by one following this patter:
image.jpg
image1.jpg
image2.jpg
The problem comes on the 4th image, it comes back with 0.jpg.
Here is the relevant code:
...
$filetarget = $this->make_image_filename($directory, $new_filename, $extension);
if(!move_uploaded_file($file['tmp_name'], $filetarget)){
$error[$index] = 'copy';
}
...
private function make_image_filename($directory, $name = '', $extension){
if(empty($name)) $name = 'NULL';
$filetarget = $directory.$name.$extension;
if(file_exists($filetarget)){
$name = $this->increment_filename($name);
return $this->make_image_filename($directory, $name, $extension);
} else {
return $filetarget;
}
}
private function increment_filename($name){
$index = $this->get_filename_index($name);
if(is_numeric($index)){
$pos = strpos($name, $index);
$name = substr($name, 0, $pos);
}
if(is_null($index)){
$index = 0;
}
++$index;
return $name.$index;
}
private function get_filename_index($name){
// CHECK FOR INDEX
$i = 1;
$index = substr($name, -$i);
$last_chars = substr($name, -$i);
while(is_numeric($last_chars)){
++$i;
$last_chars = substr($name, -$i);
if(is_numeric($last_chars)){
$index = $last_chars;
}
}
if(is_numeric($index)){
return $index;
} else {
return NULL;
}
}
I am in the process now of isolating this code on my local server to run some tests. Can you see anything inherently flawed in this process?
Here is a function I use to do the same thing:
function make_unique($full_path) {
$file_name = basename($full_path);
$directory = dirname($full_path).DIRECTORY_SEPARATOR;
$i = 2;
while (file_exists($directory.$file_name)) {
$parts = explode('.', $file_name);
// Remove any numbers in brackets in the file name
$parts[0] = preg_replace('/\(([0-9]*)\)$/', '', $parts[0]);
$parts[0] .= '('.$i.')';
$new_file_name = implode('.', $parts);
if (!file_exists($new_file_name)) {
$file_name = $new_file_name;
}
$i++;
}
return $directory.$file_name;
}
(except it make file names like image(1).jpg image(2).jpg)
How about this:
function get_next_file_name($file) {
if (!preg_match('/^(\D+)(\d*)(\.\S+)$/', $file, $match)) {
throw new Exception('bad file name format');
}
return $match[1] . (empty($match[2]) ? 1 : ($match[2] + 1)) . $match[3];
}
echo get_next_file_name('image.jpg'), "\n"; // prints image1.jpg
echo get_next_file_name('image1.jpg'), "\n"; // prints image2.jpg
echo get_next_file_name('image999.jpg'), "\n"; // prints image1000.jpg
I have many PDFs in a folder. I want to extract the text from these PDFs using xpdf. For example :
example1.pdf extract to example1.txt
example2.pdf extract to example2.txt
etc..
here is my code :
<?php
$path = 'C:/AppServ/www/pdfs/';
$dir = opendir($path);
$f = readdir($dir);
while ($f = readdir($dir)) {
if (eregi("\.pdf",$f)){
$content = shell_exec('C:/AppServ/www/pdfs/pdftotext '.$f.' ');
$read = strtok ($f,".");
$testfile = "$read.txt";
$file = fopen($testfile,"r");
if (filesize($testfile)==0){}
else{
$text = fread($file,filesize($testfile));
fclose($file);
echo "</br>"; echo "</br>";
}
}
}
I get blank result. What's wrong with my code?
try using this :
$dir = opendir($path);
$filename = array();
while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
$content = shell_exec('C:/AppServ/www/pdfs/pdftotext '.$filename.' ');
$read = strtok ($filename,".");
$testfile = "$read.txt";
$file = fopen($testfile,"r");
if (filesize($testfile)==0){}
else{
$text = fread($file,filesize($testfile));
fclose($file);
echo "</br>"; echo "</br>";
}
}
You do not have to create a temporary txt file
$command = '/AppServ/www/pdfs/pdftotext ' . $filename . ' -';
$a = exec($command, $text, $retval);
echo $text;
if it does not work check the error logs of the server.
The lines
echo "</br>";
echo "</br>";
should be
echo "</br>";
echo $text."</br>";
Hope this helps
I have server output that looks like this
PLAYER_ENTERED name ipaddress username
If the string contains PLAYER_ENTERED there will always be 3 spaces within the string separating it (how can this be modified so it does this too?). I would like to print out only the ipaddress and username (last 2 sections).
How can this be done?
This is code that prints out the whole thing:
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while (($line = fgets($f)) !== FALSE)
{
if (strstr($line, $q))
{
print "<li>$line";
}
I imagine this using explode() but I've given up trying since I hardily know how to code php.
Desired Output
username ipaddress
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while (($line = fgets($f)) !== FALSE)
{
if (strstr($line, $q))
{
$data = explode(" ", $line); // split using the space into an array
// array index 0 = PLAYER_ENTERED
print "IP:" . $data[1]; // array index 1 = IP
print "Name: " . $data[2]; // array index 2 = name
}
}
You can use substr()to check if the first 14 characters of $line equals PLAYER_ENTERED and then you use list() and explode() to extract the data from the line.
$q = $_REQUEST["ipladder"];
$f = fopen("ladderlog.txt", "r");
while(($line = fgets($f)) !== FALSE)
{
if(substr($line, 0, 14) == 'PLAYER_ENTERED'){
list($event, $name, $ip, $username) = explode($string); // here they come!
echo 'Name: ' . $name . ', ip: ' . $ip . ', username: ' . $username;
}
}
try this ...
<?
$str = "PLAYER_ENTERED name 108.21.131.56 username";
if ( preg_match( "~^(.+)\s+(.+)\s+([\d\.]+)\s+(.+)$~msi", $str, $vv ))
echo $vv[3] . " and " .$vv[4] ;
else "N/A";
?>
IMHO Perl regexp - is the right Way to parse strings ...
One way would be:
$tokens = explode(' ', $line);
if (count($tokens) == 4 && $tokens[2] == $q) {
printf('IP: %s Username: %s', $tokens[2], $tokens[3]);
}
<?php
$str = 'PLAYER_ENTERED name 108.21.131.56 username';
$data = explode(" ", $str )
print_r($data)
?>