How to comment in and out php code inside a file - php

Using PHP how to comment in all php code inside certain php file
for example if i've the followig file
$file = 'myfile.php';
has only PHP code
<?php
$c = 'anything';
echo $c;
?>
I want using PHP to comment in (add /* just after open tag <?php and */ just before close tag ?>) to be
<?php
/*
$c = 'anything';
echo $c;
*/
?>
And also how to do the reverse bycomment out (remove /* */) to return back to
<?php
$c = 'anything';
echo $c;
?>
I've been thinking to use array_splice then doing str_replace then using implode and file_put_contents but still unable to figure out how to do this.
Update
Okay meanwhile getting some help over here, i was thinking about it and it comes to my mind this idea .... USING ARRAY!
to add block comment /* just after open tag <?php i will convert the content of that file into array
$contents = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
and then i can array push new element at position 2 with /*
and to do the reverse i will use unset($contents[1]); to unset element at postion 2 which means, /* will be gone
later on i can file_put_contents($file, $contents); to re-write the file again.

You can use PREG_REPLACE :
<?php
function uncomment($file_path) {
$current = file_get_contents($file_path);
$current = preg_replace('/\\/\\*(.+?)\\*\\//s', '$1', $current);
file_put_contents($file_path, $current);
return $current;
}
echo "<plaintext>" . uncomment("code.php");
?>
BEFORE :
AFTER :

I don't know why you want comment or uncomment the php code but I don't think it's a good way to do. I advice you to use variable or constant, like this :
One other way to enable or disable you code, is to use constant variable after the second time :
TOGGLE/UNTOGGLE COMMENT :
You will be able to do :
uncomment("code.php", "MYENV_DEBUG"); // uncomment
uncomment("code.php", "MYENV_DEBUG"); // comment
uncomment("code.php", "MYENV_DEBUG"); // uncomment
uncomment("code.php", "MYENV_DEBUG"); // comment
FIRST TIME :
SECOND TIME :
THIRD TIME :
Code :
<?php
function uncomment_header($name, $value) {
return '<?php define("' . $name . '", ' . $value . '); ?>';
}
function uncomment($file_path, $name) {
$current = file_get_contents($file_path);
$regex = '/<\\?php define\\("' . $name . '", (0|1)\\); \\?>/';
if (preg_match($regex, $current, $match)) {
$value = ($match[1] == 1) ? 0 : 1;
$current = preg_replace($regex, uncomment_header($name, $value), $current);
} else {
$header = uncomment_header($name, 1) . "\n";
$start = 'if (' . $name . '):';
$end = 'endif;';
$current = $header . $current;
$current = preg_replace('/\\/\\*(.+?)\\*\\//s', $start . '$1' . $end, $current);
}
file_put_contents($file_path, $current);
return $current;
}
echo "<plaintext>" . uncomment("code.php", "MYENV_DEBUG");
?>

There are two types of comments in PHP 1)single line comment 2)Multiple line comment for single comment in php we just type // or # all text to the right will be ignored by PHP interpreter. for example
<?php
echo "code in PHP!"; // This will print out Hello World!
?>
Result: code in PHP!
For multiple line comments multiple line PHP comment begins with " /* " and ends with " / " for example
<?php
/* This Echo statement will print out my message to the
the place in which I reside on. In other words, the World. */
echo "Hello World!";
/* echo "My name is Noman Ali!";
echo "PHP Programmer!";
*/?>
Result: Hello World!

Like this:
#canned test data, a string and the file contents are the same
$contents = <<<'CODE'
<?php
$c = 'anything';
echo $c;
?>
CODE;
$contents = preg_replace(['/<\?php\s/','/\?\>/'], ['<?php/*', '*/?>'], $contents);
echo $contents;
Output
<?php/*
$c = 'anything';
echo $c;
*/?>
Sandbox
NOTE - this will only work if the ending tag is present. In PHP the ending tag is actually optional. This will also not work on things like short tags <? or <?= although it will catch the ending tags.
Because of these edge cases it's very hard to do with regex (or any string replacement).
Valid examples of PHP code
<?php
$c = 'anything';
echo $c;
?>
//-------- no ending tag ---------
<?php
$c = 'anything';
echo $c;
//------- short tags ---------
<? echo 'foo'; ?>
//------- short echo tags ---------
<?= $foo; ?>
etc...
Good luck if you want to try to catch them all....

Related

extract pure text strings from php scripts for translation

I have project which contains bigger amount of php files. Former programmer wrote everything (texts) in english in source files together with html code and I need to make translation now. Go manually file by file and extract all texts to one lanugage file is huge pain. Is there any free tool please to extract and convert all text to e.g. variables in source files and produce just one big file with text variables to simple translation?
many thanks.
P.S. I would like to automatize this work rather than manually do it file-by-file.
Examples of code in php files:
<?php
echo "Hi back, " . $user;
?>
<center class="title">No list(s) available.</center>
<tr id="exp<?php echo $r; ?>" class="me" onmouseover="dis('<?php echo $u; ?>');"> <td>This is new statement</td></tr>
this function is gonna help you in some cases and it returns the plain text between > and <
before you start you need to replace
' (quotation)
with
\' (backslash quotation)
$text = '
<?php
echo "Hi back, " . $user;
?>
<center class="title">No list(s) available.</center>
<tr id="exp<?php echo $r; ?>" class="me" onmouseover="dis(\'<?php echo $u; ?>\');"> <td>This is new statement</td></tr>
';
the function is:
function getSentences($string){
$arr = array();
$parts = explode(">", $string);
if(count($parts) > 2){
$pattern = "/\>(.*?)</";
foreach($parts as $part){
$part = ">" . $part;
preg_match($pattern, trim($part), $matches);
if(!empty($matches[1]) AND $matches[1] != " "){
if(preg_match('/^[a-zA-Z0-9]/', $matches[1])){
$arr[] = $matches[1];
}
}
}
}else{
$pattern = "/\>(.*?)</";
preg_match($pattern, $string, $matches);
$arr[] = $matches[1];
}
return $arr;
}
and call the function by :
print_r(getSentences($text));
the output will be something like this:
Array ( [0] => No list(s) available. [1] => This is new statement )

How can echo the string in PHP to output variable “$_GET" and “[ ]"?

I have a script that read in a text file using foreach loop, but the string is unable to recognize "$_GET" or "[ ]" to display or to echo out the string. If the the echo works correctly then I can append the string output to another php file to execute, but I'm not able to make the string to echo appropriately. Please advice. Thx
<?php
$filename = "./client.txt";
echo $filename ."\n"."<br>" ;
$contents = file($filename);
foreach ($contents as $line) {
$line = str_replace(PHP_EOL, '', $line);
$str = " $$line=$_GET["$line"]; " ;
echo $str;
}
?>
--------------------------------------
Text file: client.txt
DEPLOYMENT_ID
CLINICAL_APP
ZOO_MAX
SVN_REPO
---------------------------------------
Echo output should be:
$DEPLOYMENT_ID=$_GET["DEPLOYMENT_ID"];
$CLINICAL_APP=$_GET["CLINICAL_APP"];
$ZOO_MAX=$_GET["ZOO_MAX"];
$SVN_REPO=$_GET["SVN_REPO"];
If you just want to echoing it, use ' single quote inside GET :
$str = " $$line=$_GET['" . $line . "'] " ;
you can use sprintf
like sprintf("$%s=\$_GET['%s']",$line,$line);

Create a php file with the value of echo values

I have a piece of code like this:
$classVoHeader = 'class C'.toCamelCase($tableName,true).'Vo{';
$classVoFooter = '}';
$str ='public $table_map = array(';
$propertyStr = '';
foreach($columnInfos as $column){
$str.=$br.'\''.$column['Field'].'\' => \''.toCamelCase($column['Field']).'\',';
$propertyStr.=$br.'public $'.toCamelCase($column['Field']).';';
}
$str.=$br.');';
echo $classVoHeader.$br;
echo $str;
echo $propertyStr.$br;
echo $classVoFooter;
And I want to create a php file that have content is all of what it echoed.
Is it impossible?
Take a look at http://www.php.net/manual/en/function.ob-get-contents.php to save what is being printed into a buffer, then use http://www.php.net/manual/en/function.file-put-contents.php to save this string to a file
Strange question but, here you go:
$Result = '<?php ' . $classVoHeader.$br . $str . $propertyStr.$br . $classVoFooter . ' ?>';
$file = fopen("result.php","w");
echo fwrite($file,$Result);
fclose($file);
i dont know what your code is and it doesnt matter. With my answer you will have all the output that is produced between ob_start(); and ob_get_clean(); saved to the variable $the_output_of_code. Then just write this to a file.
<?php
ob_start();
// your code begins here
// [your piece of code here whatever]
$classVoHeader = 'class C'.toCamelCase($tableName,true).'Vo{';
$classVoFooter = '}';
$str ='public $table_map = array(';
$propertyStr = '';
foreach($columnInfos as $column){
$str.=$br.'\''.$column['Field'].'\' => \''.toCamelCase($column['Field']).'\',';
$propertyStr.=$br.'public $'.toCamelCase($column['Field']).';';
}
$str.=$br.');';
echo $classVoHeader.$br;
echo $str;
echo $propertyStr.$br;
echo $classVoFooter;
// your code ends here
$the_output_of_code = ob_get_clean();
$file = fopen("the_output.php","w");
fwrite($file,$the_output_of_code);
fclose($file);
?>

Display white spaces that precede the content of the line of the file - PHP

I'm currently using foreach loop to display the contents of a text file. However, I want to also display the whitespaces that precede the actual content of the line. How to do so?
$loop_var = 0;
foreach($lines as $line) {
$loop_var++;
if ($loop_var == 1) {
echo'<div id="h1">' . $line . '</div>';
}
if ($loop_var == 2) {
echo '<div id="h2">' . $line . '</div><br />';
}
if ($loop_var > 2) {
if ($loop_var == 3) { echo '<pre><div id="code">'; }
echo ($line) . "<br />";
}
}
echo '</pre></div>';
Now, if the textfile contains the following:
blah
blah
blah
blah
It is getting displayed as:
blah
blah
blah
blah
Use <pre> tag, and print the content of textfile into this.
example:
print '<pre>'.file_get_contents('filename.txt').'</pre>';
Line By line (With conditions)
$file = fopen('filename','r');
print '<pre>';
$counter = 0;
while( $line = fgets($file) ){
if( /*the condition comes here whitch line you want to print. example: */ $counter >= 2 ){
print $line;
}
if( /*the condition comes here where wants you end the printing. example: */ $counter >= 10 )
$counter++;
}
print '</pre>';
fclose($file);
When you read text from a file and output that text again, the whitespace is still there.
But: if you are outputting HTML, and viewing the output in a browser, the whitespace is ignored. That's just the normal way html is displayed by a browser.
Use your browser to view the HTML source code (e.g. CTRL-U in firefox) to check if this is the case.
If you want the whitespace to be displayed in your webpage you can use the pre-Tag, or use the CSS property "whitespace" http://www.w3schools.com/cssref/pr_text_white-space.asp.
<pre><?php echo $file_content ?></pre>
or
<p style="whitespace:pre;"><?php echo $file_content ?></p>
See demo here: http://jsfiddle.net/bjelline/CjXMe/
Well, you can brute-force it if you wish ... only in case you're really stuck!
1) Get the length of the string with strlen()
2) Run a loop on the characters in the string and check for a space with strpos
3) Concatenate an html space to an empty string and print before-hand
$str = " whatever is in here ... ";
$spaces = "";
for( $i=0; $i<strlen($str); $i++ ){
if( strpos( $str, ' ', $i ) ){
$spaces .= " ";
}
}

PHP create page as a string after PHP runs

I'm stuck on how to write the test.php page result (after php has run) to a string:
testFunctions.php:
<?php
function htmlify($html, $format){
if ($format == "print"){
$html = str_replace("<", "<", $html);
$html = str_replace(">", ">", $html);
$html = str_replace(" ", "&nbsp;", $html);
$html = nl2br($html);
return $html;
}
};
$input = <<<HTML
<div style="background color:#959595; width:400px;">
<br>
input <b>text</b>
<br>
</div>
HTML;
function content($input, $mode){
if ($mode =="display"){
return $input;
}
else if ($mode =="source"){
return htmlify($input, "print");
};
};
function pagePrint($page){
$a = array(
'file_get_contents' => array($page),
'htmlify' => array($page, "print")
);
foreach($a as $func=>$args){
$x = call_user_func_array($func, $args);
$page .= $x;
}
return $page;
};
$file = "test.php";
?>
test.php:
<?php include "testFunctions.php"; ?>
<br><hr>here is the rendered html:<hr>
<?php $a = content($input, "display"); echo $a; ?>
<br><hr>here is the source code:<hr>
<?php $a = content($input, "source"); echo $a; ?>
<br><hr>here is the source code of the entire page after the php has been executed:<hr>
<div style="margin-left:40px; background-color:#ebebeb;">
<?php $a = pagePrint($file); echo $a; ?>
</div>
I'd like to keep all the php in the testFunctions.php file, so I can place simple function calls into templates for html emails.
Thanks!
You can use output buffering to capture the output of an included file and assign it to variable:
function pagePrint($page, array $args){
extract($args, EXTR_SKIP);
ob_start();
include $page;
$html = ob_get_clean();
return $html;
}
pagePrint("test.php", array("myvar" => "some value");
And with test.php
<h1><?php echo $myvar; ?></h1>
Would output:
<h1>some value</h1>
This may not be exactly what you're looking for but it seems you want to build an engine of sorts for processing email templates into which you can put php functions? You might check out http://phpsavant.com/ which is a simple template engine that will let you put in php functions directly into a template file as well as basic variable assignment.
I'm not sure what printPage is supposed to be doing but I would re-write it like this just to make it more obvious because the array of function calls is a bit complicated and I think this is all that is really happening:
function pagePrint($page) {
$contents = file_get_contents($page);
return $page . htmlify($contents,'print');
};
and you might consider getting rid of htmlify() function and use either of the built-in functions htmlentities() or htmlspecialchars()
Seems like my original method may not have been the best way of going about it. Instead of posing a new question on the same topic, figured it was better to offer an alternate method and see if it leads to the solution I am after.
testFunctions.php:
$content1 = "WHOA!";
$content2 = "HEY!";
$file = "test.html";
$o = file_get_contents('test.html');
$o = ".$o.";
echo $o;
?>
text.php:
<hr>this should say "WHOA!":<hr>
$content1
<br><hr>this should say "HEY!":<hr>
$content2
I'm basically trying to get $o to return a string of the test.php file, but I want the php variables to be parsed. as if it was read like this:
$o = "
<html>$content1</html>
";
or
$o = <<<HTML
<html>$content1</html>
HTML;
Thanks!

Categories