I've searched and searched. I can't find the solution. I have a string that goes a little something like this: ABC_test 001-2.jpg
I also have this bit of code:
$makeSpace = preg_replace("/[^a-zA-Z0-9\s]/", " ", $replaceUnder);
However, this bit of code will not replace the underscore (_). In fact, the output of this variable is: ABC
So it stops once it hits the underscore. I need to replace EVERY possible non-alphanumeric character, including the underscore, asterisks, question marks, whatever. What am I missing?
Thanks for the help.
EDIT:
<?php
//set images directory
$directory = 'ui/images/customFabrication/';
try {
// create slideshow div to be manipulated by the above jquery function
echo "<div class=\"slideLeft\"></div>";
echo "<div class=\"sliderWindow\">";
echo "<ul id=\"slider\">";
//iterate through the directory, get images, set the path and echo them in img tags.
foreach ( new DirectoryIterator($directory) as $item ) {
if ($item->isFile()) {
$path = $directory . "" . $item;
$class = substr($item, 0,-4); //removes file type from file name
//$replaceUnder = str_replace("_", "-", $class);
$makeDash = str_replace(" ", "-", $replaceUnder);
$replaceUnder = preg_replace("/[^a-zA-Z0-9\s]/", " ", $class);
//$makeSpace = preg_replace("/[^a-zA-Z0-9\s]/", " ", $replaceUnder);
echo "<li><img rel=" . $replaceUnder . " class=" . $class . " src=\"/ui/js/timthumb.php?src=/" . $path . "&h=180&w=230&zc=1\" /></li>";
}
}
echo "</ul>";
echo "</div>";
echo "<div class=\"slideRight\"></div>";
}
//if directory is empty throw an exception.
catch(Exception $exc) {
echo 'the directory you chose seems to be empty';
}
?>
I can't reproduce your problem, for me the string that gets outputted is:
$replaceUnder = 'ABC_test 001-2.jpg';
$makeSpace = preg_replace("/[^a-zA-Z0-9\s]/", " ", $replaceUnder);
print_r($makeSpace);
# output:
# ABC test 001 2 jpg
.
dubugging your code
I went through the code you pasted in and found a few errors, which are maybe related, maybe not:
I get an error on this line, because replaceUnder is not defined:
$makeDash = str_replace(" ", "-", $replaceUnder);
since you commented this line out:
//$replaceUnder = str_replace("_", "-", $class);
I guess you meant to comment it out as well. It's not clear at all what you're trying to do and why you have all those replace statements. If you're just trying to echo out the file names with all the symbols replaced, this is how I did it and the letters all got replaced with spaces:
<?php
//set images directory
$directory = './';
try {
foreach ( new DirectoryIterator($directory) as $item ) {
if ($item->isFile()) {
$path = $directory . "" . $item;
// remove ending/filetype - the other method doesn't support 4 letter file endings
$name = basename($item);
$fixedName = preg_replace("/[^a-zA-Z0-9\s]/", " ", $name);
echo "Name: $fixedName\n";
}
}
}
//if directory is empty throw an exception.
catch(Exception $exc) {
echo 'the directory you chose seems to be empty';
}
?>
I think your whole problems stem from the naming of variables. Consider turning on notice errors - they will let you know if you're referencing variables that aren't defined.
Related
I am creating a 'delete account' function for users of a site if they want to delete all of their details.
Deleting the relevant records from the database has been pretty straight forward. However, I want to deleted the images they have saved in the site's images folder.
Below is the code I'm trying, a part of which is based on #kmoser's suggestion.
// $db_image_id, $db_image_ext, $db_image_filename are fetched in a previous code block for when images are outputted on the page.
if(isset($_POST['delete-account'])) {
$loggedInUser = $_SESSION['logged_in'];
$imagesLibrary = 'images-lib/';
$imagesDownload = 'images-download/';
try {
$s = $connection->prepare("SELECT filename FROM `imageposts` WHERE user_id = :user_id");
$s->bindParam(':user_id', $loggedInUser);
$s->execute();
// -- DELETE THE USER'S IMAGE FILES FROM 'IMAGES-LIB' FOLDER
while ($row = $s->fetch()) {
if (isset($pattern)) {
$pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}' . '.' . $row['file_extension'];
foreach (glob($pattern, GLOB_BRACE) as $filenames) {
unlink($filenames);
}
}
}
header("Location: index.php");
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
The key piece of the above code is this snippet below:
// -- DELETE IMAGE FILES FROM 'IMAGES-LIB' FOLDER
while ($row = $s->fetch()) {
if (isset($pattern)) {
$pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}' . '.' . $row['file_extension'];
foreach (glob($pattern, GLOB_BRACE) as $filenames) {
unlink($filenames);
}
}
}
I was initially getting an error PHP Notice: Undefined index: file_extension in /Applications/MAMP/htdocs/site/profile-edit.php in relation to the 3rd line of PHP code above that declares the $pattern variable. I've managed to fix this by wrapping the code in the if(isset($pattern)) if statement that is now present. I don't get any error logs now, but the files are not being deleted out of the 'images-lib' directory.
A typical filename example is 6146972e2dc73_1632016174-500.jpeg
Here is an example of how the files look in the database:
When outputted onto a page in an <img> tag, the size e.g. -500 part of the filename is concatenated on with a string inside the src attribute.
src="<?php echo '/images-lib/' . $db_image_filename . '-500' . '.' . $db_image_ext; ?>"
Any help or assistance on how to delete images specific to a user from the images directory would be wonderful.
There's no need to store the filenames and extensions in separate arrays, or even in an array at all. Just fetch every image filename and extension in a loop, assemble it into a pattern (e.g. images/6146972e2dc73_1632016174-{500,750,1000,1500}.jpeg, then glob() the pattern to find each matching file and unlink it:
while ($row = $s->fetch()) {
$pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}.' . $row['file_extension'];
foreach (glob($pattern, GLOB_BRACE) as $filename) {
unlink($filename);
}
}
I have problem with files, for example .342342.jpg or .3423423.ico. The script below dosen't see this files. My script:
<?php
$filepath = recursiveScan('/public_html/');
function recursiveScan($dir) {
$tree = glob(rtrim($dir, '/') . '/*');
if (is_array($tree)) {
foreach($tree as $file) {
if (is_dir($file)) {
//echo $file . '<br/>';
//recursiveScan($file);
} elseif (is_file($file)) {
echo $file . '<br/>';
if (preg_match("[.a-zA-Z0-9]", $file )) {
echo $file . '<br/>';
//unlink($file);
}
}
}
}
}
?>
Use this \.[[:alnum:]]*as your regular expression to match a single dot and then any number of letters and digits afterwards, because as you're using it now it only matches a single character of any kind. Use regex101.com for future regular expression testing. It shows a detailed breakdown of what you're filtering for and has a great cheatsheet for all tokens you can use
AFAIK, glob doesn't return filenames that begin with a dot, so, .342342.jpg is not returned.
Your regex if (preg_match("[.a-zA-Z0-9]", $file )) { matches filenamess that contain .a-zA-Z0-9 (ie. xxx.a-zA-Z0-9yyy) I guess you want filenames that contain dot or alphanum, so your regex becomes:
if (preg_match("/^[.a-zA-Z0-9]+$/", $file )) {
I am trying to configure the Eclipse PHP formatter to keep the opening and closing php tags on 1 line if there is only 1 line of code between them (while keeping the default new line formatting if there are more lines of code).
Example:
<td class="main"><?php
echo drm_draw_input_field('fax') . ' ' . (drm_not_null(ENTRY_FAX_NUMBER_TEXT) ? '<span class="inputRequirement">' . ENTRY_FAX_NUMBER_TEXT . '</span>' : '');
?></td>
Should be formatted to:
<td class="main"><?php echo drm_draw_input_field('fax') . ' ' . (drm_not_null(ENTRY_FAX_NUMBER_TEXT) ? '<span class="inputRequirement">' . ENTRY_FAX_NUMBER_TEXT . '</span>': ''); ?></td>
Is there any way to achieve this with Eclipse? Or another suggestion/formatter?
EDIT:
It seems Eclipse does not have such a formatting option, as explained in the comments below. Any existing alternatives that can do this?
As i already mentioned under question comment "As i know you can't do such thing in eclipse as eclipse has only options to format code part i mean the text part inside php tags <?php ...code text... ?>"
But you can achieve it with this php script
Very important before start: Backup your php project which you are going to mention in dirToArray() function
// Recursive function to read directory and sub directories
// it build based on php's scandir - http://php.net/manual/en/function.scandir.php
function dirToArray($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value){
if (!in_array($value,array(".",".."))){
if (is_dir($dir . DIRECTORY_SEPARATOR . $value)){
$result = array_merge(
$result,
dirToArray($dir . DIRECTORY_SEPARATOR . $value)
);
}else{
$result[] = $dir . DIRECTORY_SEPARATOR . $value;
}
}
}
return $result;
}
// Scanning project files
$files = dirToArray("/home/project"); // or C:/project... for windows
// Reading and converting to single line php blocks which contain 3 or less lines
foreach ($files as $file){
// Reading file content
$content = file_get_contents($file);
// RegExp will return 2 arrays
// first will contain all php code with php tags
// second one will contain only php code
// UPDATED based on Michael's provided regexp in this answer comments
preg_match_all( '/<\?php\s*\r?\n?(.*?)\r?\n?\s*\?>/i', $content, $blocks );
$codeWithTags = $blocks[0];
$code = $blocks[1];
// Loop over matches and formatting code
foreach ($codeWithTags as $k => $block){
$content = str_replace($block, '<?php '.trim($code[$k]).' ?>', $content );
}
// Overwriting file content with formatted one
file_put_contents($file, $content);
}
NOTE: This is just simple example and of course this script can be improved
// Result will be that this
text text text<?php
echo "11111";
?>
text text text<?php
echo "22222"; ?>
text text text<?php echo "33333";
?>
<?php
echo "44444";
echo "44444";
?>
// will be formated to this
text text text<?php echo "11111"; ?>
text text text<?php echo "22222"; ?>
text text text<?php echo "33333"; ?>
<?php
echo "44444";
echo "44444";
?>
In sublimetext, the manual command is ctrl + J.
Automagically, might i suggest you take a look at this:
https://github.com/heroheman/Singleline
I recently started working on a PHP File Manager for my server, as I figured it'd be extremely convient to use, as well as allowing me to brush up on my PHP Skills. Anyways, I have a few questions that I hope can be answered...
When I list my directorys, there are always a couple of "Dots". For example: ., .., Folder_1, Folder_2, etc... How would I go about removing those "Dots" from my directory list?
When I list my directorys, my current method has no problem listing folders with underscores, or ones that have no space in the name. However, it cannot handle Folders with space's in their names. Is there a way to get my File Manager to recognize and handle spaces in the names properly?
Here is my current code...
<?php
global $dir_path;
if (isset($_GET["directory"])) {
$dir_path = $_GET["directory"];
//echo $dir_path;
}
else {
$dir_path = $_SERVER["DOCUMENT_ROOT"]."/";
}
$directories = scandir($dir_path);
foreach($directories as $entry) {
if(is_dir($dir_path . "/" . $entry )) {
echo "<li>" . $entry . "</li>";
}
else {}
}
?>
Much thanks for any help,
Brandon
P.S. Are the "Dots" related to my server's ext4 file-system? It's not really significantly pertinent to my problems, I'm just a tad curious.
If you just want a simple version :
foreach($directories as $entry) {
if (is_dir($dir_path . "/" . $entry) && !in_array($entry, array('.','..'))) {
echo "<li>" . $entry . "</li>";
}
else {}
}
this checks for . / .. eg current dir and back dir. Regarding the spaces it sounds weird. Is it the link that is not working or is it scandir? If it is the links, replace blanks with %20, eg
$href="?directory=" . $dir_path . "" . str_replace(' ','%20',$entry) . "/";
echo "<li>' . $entry . '</li>';
more likely I think it is the lack of quotes "" around href, eg
echo '<li>' . $entry . '</li>';
instead. When you are not adding quoutes, a link with blanks, say "test 123" will be interpreted as href=test by the browser, because there is nothing that encapsulates the whole link. It should be href="test 123".
i have a wordpress inside Public html folder on server.
i want to dispaly images from the folder Public_html--->Trial-->Wordpress_site-->uploads
below is page.php code
<?php
$directory = dirname(__FILE__).'/uploads';
echo $directory;
try {
// Styling for images
foreach ( new DirectoryIterator("/" . $directory) as $item ) {
if ($item->isFile()) {
echo "<div class=\"expand_image\">";
$path = "/" . $directory . "/" . $item;
echo $path;
echo "<img src=/"". $path . "\" width=861 height=443 />";
echo "</div>";
}
}
}
catch(Exception $e) {
echo 'No images found for this player.<br />';
}
?>
The images arent getting displayed..
anyone knows about the same??
edit1
I think there is problem in this sentence
echo "<img src=/"". $path . "\" width=861 height=443 />";
is it?
edit2
//home/softwar2/public_html/Pradnnya_blog/wordpress_site/wp-content/themes/deep-red/our_results/4thpanelfinal.jpg
is the path that i get when echoed.
__FILE__ gives you the path of the current file on the filesystem; however, when you visit the webpage and you see a link in the tag, you'll try to access that as a URL instead of a file. For this, you might find $_SERVER['PHP_SELF'] useful, or another one of the $_SERVER elements. It might be better to have the URL in a configuration file though, because $_SERVER may sometimes not be set.
Good catch, there's a bit of a syntax error:
echo "<img src=\"". $path . "\" width=861 height=443 />";
You'll want to use the backslash to escape the double quote.