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>"
Related
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
The current code provided on previous question is working. I need help to modify it so I can tell it what php files to combine.
The code below combines every .php file it finds in a directory.
(ie: Need to combine only the following pages, page1.php, page2.php, page3.php, page4.php, page5.php, page6.php, page7.php, page8.php, page9.php, page10.php, page11.php, page12.php )
Thanks in advance.
<?php
foreach (glob("*.php") as $filename) {
$code.=file_get_contents("./$filename");
}
file_put_contents("./combined.php",$code);
?>
If you know the file names and they are not going to change then you can do this:
<?php
$files = array("a.php", "b.php", "c.php");
$comb;
foreach ($files as $k)
{
$comb .= file_get_contents("./".$k);
}
file_put_contents("./combined.php",$comb);
?>
If you are getting them from a form submission then do something like this:
<?php
$files = array();
foreach ($_POST['files_to_combine'] as $k)
{
$files .= $k;
}
$comb;
foreach ($files as $k)
{
$comb .= file_get_contents("./".$k);
}
file_put_contents("./combined.php",$comb);
?>
** As a security note please make sure to sanitize your inputs if you use the second method! this code is only a proof of concept to make it simple to understand and use.
I have no idea why I get negative on my question asking to have it modified seeing how the programmer that answered it copied it from another site.
I don't do this for a living and have no plans too. These are personal
things I try to do to make my job go easier and without paper.
So here is the answer.
<?php
$txt1 = file_get_contents('page-001.php');
$txt1 .= "\n" . file_get_contents('page-002.php');
$txt1 .= "\n" . file_get_contents('page-003.php');
$txt1 .= "\n" . file_get_contents('page-004.php');
$txt1 .= "\n" . file_get_contents('page-005.php');
$txt1 .= "\n" . file_get_contents('page-006.php');
$txt1 .= "\n" . file_get_contents('page-007.php');
$txt1 .= "\n" . file_get_contents('page-008.php');
$txt1 .= "\n" . file_get_contents('page-009.php');
$txt1 .= "\n" . file_get_contents('page-010.php');
$txt1 .= "\n" . file_get_contents('page-011.php');
$txt1 .= "\n" . file_get_contents('page-012.php');
$fp = fopen('newcombined.php', 'w');
if(!$fp)
die('Could not create / open text file for writing.');
if(fwrite($fp, $txt1) === false)
die('Could not write to text file.');
echo 'Text files have been merged.';
?>
Hi I am trying to get images to load into a page using the file names from an array,
This is what I have so far
<?php
$i=0;
$img=array("1.png","2.png","3.png","4.png");
while ($i<count($img))
{
echo "<img class='loadin' alt='imgg' src=" . "'http://www/images/" . $img[i] . "'" . "/" . ">" . "<br/>";
$i++;
}
?>
It seems to ignore the file name and just enters:
http://www/images/
as the source and ignores the file name from the array
Any Help would be great Thanks
Mikey
You forgot the dollar sign with your $i variable: $img[$i]
EDIT:
(btw. using a foreach-loop would be easier...)
foreach($img AS $filename) {
echo "<img class='loadin' alt='imgg' src='http://www/images/" . $filename . "'/><br/>";
}
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.