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
Related
I m using this code to output content of files in a directory but I have two problems
first is that this directory contains sub-dir and this code doesn't output
files content in these sub-dir
Second problem
I want this code to output like
Filename:"name of the file"
Content :"content of the file"
so that I can parse this
$dir = new DirectoryIterator('./Chemistry');
foreach($dir as $file)
{
if(!$file->isDot() && $file->isFile() && strpos($file->getFilename(), '.md') !== false)
{
$content = file_get_contents($file->getPathname());
echo $content
}
}
?>
If I understand correct you want to output:
echo 'Filename: ' . $file->getFilename() . ' Content: ' . $content;
If this is not your intention I will require a more thorough explanation.
* edit *
For dir iteration use http://php.net/manual/en/function.scandir.php
From the top of my head it goes a little something like this (hit it)...
function loopDir($path) {
$allFilesAndFoldersInCurrentFolder = scandir($path);
foreach($allFilesAndFoldersInCurrentFolder as item) {
if(is_dir($item)) {
loopDir($path.'/'.$item);
}
else {
echo 'Filename: ' . $file->getFilename() . ' Content: ' . $content;
}
}
}
I have a txt file with lines in this format
this is a name|this is a type|this is a description
this is a name|this is a type|this is a description
this is a name|this is a type|this is a description
I need to access those lines and echo them like this:
<li type="this is a type" description="this is a description">this is a name</li>
I have no idea how to approach this.
Thanks in advance
Normally I wouldn't write code for you without you having provided an example of what you've tried, but in this case it's pretty basic.
Use PHP's file function to read a file into an array (line by line), then use explode to break that line up:
<?php
$contents = file('yourfile.txt');
foreach($contents as $eachline) {
list($name, $type, $description) = explode("|", $eachline);
echo '<li type="' . $type . '" description="' . $description . '">' . $name . '</li>';
}
?>
PHP manual: http://us2.php.net/manual/en/function.file.php
The first step is to read every line of the file.
How to read a file line by line in php
After that explode the string by the pipe symbol $out = explode("|", $string);
after that you have an array and you can access the values with $out[0]; for example.
This is easypeasy:
$parts = explode("|", $line);
$out = "<li type='$parts[1]' description='$parts[2]'>$parts[0]</li>"
Basically, I can write html tags/text etc etc to the file. All that is fine. However, I need to be able to write some actual php into the file and I'm completely oblivious of how I should go about doing this.
Anyway here is what I have got to help better demonstrate my situation:
$path = substr(md5(time() . md5(rand())), 0, 8);
$dir = substr(md5($_SERVER['REMOTE_ADDR']), 0, 4);
$fpath = "b/" . $dir "/" . $path;
$file = 'index.php';
$handle = fopen($fpath . '/' . $file, 'w') or die ('cannot create the file');
include template.php;
fwrite($handle, $pt1 . $pt2 . $pt3);
Inside the template.php I have variables holding a lot of html in $pt1,$pt2,$pt3
But, inbetween each 'pt' I need to have some actuall php.
So for example sake say I need $this inbetween each 'pt' and the $this being:
<?php
if(isset($_SESSION['user'])){
echo "hello";
}else{
echo "bye";
}
?>
How would I do it?
*The actual creating of the file and paths is fine though but, I know that it may look very unusual however, I like it that way. It's simply adding the php scripts to the php file.
also I have tried sticking the scripts inside variables but, it seems to just print them out as plain text in the file rather than executing them.
Does inbetween each pt means $p1 . $var . $pt2?
Try something like this:
<?PHP
$var = '<?php
if(isset($_SESSION["user"])){
echo "hello";
}else{
echo "bye";
}
?>';
echo $pt1 . $var . $pt2;
?>
Edit:
Also, you can wrap long content into a variable using
<?PHP
$var = <<< 'PHP'
<?php
if(isset($_SESSION["user"])){
echo "hello";
}else{
echo "bye";
}
?>
PHP;
$pt1 = 'before';
$pt2 = 'after';
echo "$pt1 $var $pt2";
?>
Ok sorry if its a stupid question im a begginer.
Im making a small shoutbox just for practise.
It inserts the shout infos in a txt file.
My problem is that, it lists the text from top to bottom, and i would like to do this reversed.
if(isset($_POST['submit'])) {
$text = $_POST['text'];
if(!empty($text)) {
$text = $_POST['text'];
$name = $_POST['name'];
$time = date("H:i");
$content =
"<div class='text'><em>" . $time . "</em>
<span class='c11'><b>" . "<a href='userinfo_php_willbe_here.php' target='_blank'>" . htmlspecialchars($name) . "</a>" . ":</span></b>
" . htmlspecialchars($text) . "
</div>\n";
file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
}
}
here is my code.
i was googleing around with not much luck maybe i wasnt looking hard enough.
could please someone give me a hint?
thank you
No way to do so with one function call. You need to read the content from your target file, prepend the data in php and rewrite the whole file (see file_get_contents).
$fileContent = file_get_contents($file);
$fileContent = $content . $fileContent;
file_put_contents($file, $fileContent, LOCK_EX);
You can also use the array_reverse like so:
// Data in file separated by new-line
$data = explode("\n",file_get_contents("filename.txt"));
foreach(array_reverse($data) as $value) {
echo $value."\n";
}
You can only prepend to a file by means of reading it and writing afterwards.
file_put_contents($file, $content . file_get_contents($file), LOCK_EX);
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.