Split a string by php's delimiters itself - php

I am trying to extract php code from a long file. I wish to throw away the code not in a PHP tags. Example
<html>hello world, its a wonderful day</html>
<?php echo $user_name; ?> Some more text or HTML <?php echo $datetime; ?>
I just echoed the user_name and datetime variables.
I want to return an array with:
array(
[1] => "<?php echo $user_name; ?>"
[2] => "<?php echo $datetime; ?>"
)
I think I can do this with regex but im not an expert. Any help? Im writing this in PHP. :)

You will have to view the source code in order to see the results, but this is what I came up with:
$string = '<html>hello world, its a wonderful day</html>
<?php echo $user_name; ?> Some more text or HTML <?php echo $datetime; ?>
I just echoed the user_name and datetime variables.';
preg_match_all("/<\?php(.*?)\?>/",$string,$matches);
print_r($matches[0]); // for php tags
print_r($matches[1]); // for no php tags
Update: As mentioned by Revent, you could have <?= for shorthand echo statments. It would be possible to change your preg_match_all to include this:
$string = '<html>hello world, its a wonderful day</html>
<?php echo $user_name; ?> Some more text or HTML <?= $datetime; ?>
I just echoed the user_name and datetime variables.';
preg_match_all("/<\?(php|=)(.*?)\?>/",$string,$matches);
print_r($matches[0]); // for php tags
print_r($matches[1]); // for no php tags
Another alternative is to check for <?(space) for the shorthand php statement. You can include a space (\s) to check for this:
preg_match_all("/<\?+(php|=|\s)(.*?)\?>/",$string,$matches);
I guess it just depends on how "strict", you want to be.
Update2: MikeM does make a good point, about being aware of line breaks. You may run into an instance where your tags run over into the next line:
<?php
echo $user_name;
?>
This can easily be solved by using the s modifier to skip linbreaks:
preg_match_all("/<\?+(php|=|\s)(.*?)\?>/s",$string,$matches);

Related

How to echo php code and use it?

<?php echo $row["html"]; ?>
Inside of the $row["html"] there's:
<?php $Site->Nav($owner); ?>
but when I echo it, it only echoes:
Nav($owner); ?>
How may I print the full and make it usable, which means that it will print the function Nav?
I've tried to replace <?php with [[// i the database, and just before echoing it, I change back with replace. But without success
I think you need to use eval function of php. See the example below.
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
Might be it can help.
Use eval function. It might solve your problem like this:
<?php echo eval($row["html"]); ?>
Keep the code as is in DB as if you are writing it in PHP file but without PHP opening and closing tags i.e. <?php and ?>. I haven't checked this (as i am not sure what $Site->Nav($owner); will do) but hope it would work in this case.
If I understand correctly you are wanting to output the results of $Site->Nav($owner);
I have no idea what this is expected to output, but assuming it is a string of some kind that you wish to display (hence echo) - an example of achieving this would be calling your code and have that method return the value, so you can echo it out. Ie:
function Nav($owner){
// Do your stuff
return 'Your Desired Output';
}
Then on your page you would have
<?php echo $Site->Nav($owner); ?>
Which would echo "Your Desired Output".

Output some PHP code into a HTML <code> tag

How can I use the HTML <code> element to output a block of PHP code, without the page running that PHP code? Eg;
<pre><code>
<?php
// Some super duper PHP code
?>
</code></pre>
I'm creating an API docs page, which features snippets of PHP that anyone wishing to use the API can use as examples, but anything wrapped in <?php> tags runs as an actual PHP function
Use <?php and ?>.
The HTML entities will show up as PHP opening and closing tags when the page is rendered, but PHP will obviously not see them. But you have to html-escape your code anyways, otherwise contained HTML-tags will be rendered. So there should be
<?php echo 'Hello, World.<br>'; ?>
Another way would be to have a string specified by a nowdoc and then output html-escaped (demo):
<?php
$code = <<<'EOC'
<?php
echo 'Hello, World.<br>';
// ...your code here...
?>
EOC;
echo htmlentities($code);
?>
Have look for different approaches at How do I display PHP code in HTML?.
Do this via PHP like so:
<?php
$code = '<?php
echo "Hello, World!";
?>';
echo '<code>' . htmlspecialchars($code) . '</code>';
?>
try something like this:
<?php echo '<?php'; ?>
This may help you.........
######################################################################
echo "<h2><br>Source Code of ".basename((string)__FILE__) . "</h2><hr>";
show_source(__FILE__);
echo "<hr>";
echo "<h2>Output of ".basename((string)__FILE__) . "<hr></h2>";
#######################################################################
I had to convert the less-than and greater-than to their HTML name.
<pre><code><?php echo
"<!--
This is the church title to be used in the heading of the web-pages.
Author: John Fischer III of Written For Christ in 2018
Updated:
-->
<?php echo 'Our Little Church:'; ?>" ?>
</code></pre>

Run PHP and HTML code from a string

I have a string stored in a variable in my php code, something like this:
<?php
$string = "
<?php $var = 'John'; ?>
<p>My name is <?php echo $var; ?></p>
";
?>
Then, when using the $string variable somewhere else, I want the code inside to be run properly as it should. The PHP code should run properly, also the HTML code should run properly. So, when echoing the $string, I will get My name is John wrapped in a <p> tag.
You don't want to do this. If you still insist, you should check eval aka evil function. First thing to know, you must not pass opening <?php tag in string, second you need to use single quotes for php script You want to evaluate (variables in single quotes are not evaluated), so your script should look something like:
<?php
$string = '
<?php $var = "John"; ?>
<p>My name is <?php echo $var; ?></p>
';
// Replace first opening <?php in string
$string = preg_replace('/<\?php/', '', $string, 1);
eval($string);
However, this is considered very high security risk.
So if I'm right, you have the $var = 'John'; stored in a different place.
Like this:
<?php $var = 'John'; ?>
And then on a different place, you want to create a variable named $String ?
I assume that you mean this, so I would suggest using the following:
<?php
$String = "<p>My name is ".$var." </p>";
echo $String;
?>
You should define $var outside the $string variable, like this
<?php
$var="John";
$string = "<p>My name is $var</p>";
?>
Or you can use . to concatenate the string
<?php
$var="John";
$string = "<p>My name is ".$var."</p>";
?>
Both codes will return the same string, so now when doing
<?php
echo $string;
?>
You will get <p>My name is John</p>

PHP echo function is not outputing strings in the format '<something.somethong_else>'

PHP echo function is not outputing strings in the format of html tag like <something. somethong_else>, may be because it is like HTML tags, is there any way to display it?
echo 'hi<h.i>';
Eg : this displays as
echo 'hi';
try using
<?php
echo htmlentities('hi<h.i>');
?>
You need to encode the string if you what the text to appear
echo htmlentities("hi<h.i>");
There is a thing called HTML. Where strings in <something.somethong_else> format have some meaning. Go figure.
PHP can echo out tags.
Example
<?php
echo '<p>Hello World</p>';
?>
Keep in mind, the PHP will echo where it is called. So you can also do this
<p>
<?php echo 'Hello World'; ?>
</p>
UPDATE
Since new information is sent. You can make < into < and > into > Look at HTML entities.
You probably need to use htmlentities(), try this:
echo htmlentities('hi<h.i>');

PHP's preg_match_all() to pull out all php tags

I have a large set of HTML files that I need to parse the <? and ?> tags out of, keeping in mind <?xml and the fact that an opening <?php tag doesn't need an ending tag... EOF counts too.
My regular expression knowledge is admittedly lacking: /<\?[^(\?>)]*\?>/
Example HTML:
<?
function trans($value) {
// Make sure it does not translate the function call itself
}
?>
<!-- PHP
code -->
<div id='test' <?= $extraDiv ?>>
<?= trans("hello"); ?>
<? if ($something == 'hello'): ?>
<? if ($something == 'hello'): ?>
<p>Hello</p>
<? endif; ?>
<?php
// Some multiline PHP stuff
echo trans("You are \"great'"); // I threw some quotes in to toughen the test
echo trans("Will it still work with two");
echo trans('and single quotes');
echo trans("multiline
stuff
");
echo trans("from array('test')",array('test'));
$counter ++;
?>
<p>Smart <?= $this->translation ?> time</p>
<p>Smart <?=$translation ?> time</p>
<p>Smart <?= $_POST['translation'] ?> time</p>
</div>
<?
trans("This php tag has no end");
Hoped for Array:
[0] => "<?
function trans($value) {
// Make sure it does not translate the function call itself
}
?>",
[1] => "<?= $extraDiv ?>",
[2] => etc...
No, that isn't how character classes work. Luckily you don't need to worry about that because we can use a ? to make the character class non-greedy. I'll also add a s to the end so that . can also match newlines, it usually can't.
/<\?(.*?)\?>/s
It looks like what you're looking for is lookahead and lookbehind. These regex operators basically allow you to include text in the search but omit it from the final result.
So first, you'd want to change your regex to this:
'/(?<=\<\?)[^(\?\>)]*(?=\?\>)/'
For EOF, you'd use the $ symbol. Therefore:
'/(?<=\<\?)[^(\?\>)]*(?=\?\>|$)/'
I haven't tested this but I think that should do what you're looking for, or at very least point you in the right direction.

Categories