Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string by php's delimiters itself

Tags:

string

regex

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. :)

like image 715
user1955162 Avatar asked Jan 17 '26 18:01

user1955162


1 Answers

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);
like image 89
Samuel Cook Avatar answered Jan 20 '26 06:01

Samuel Cook