-4

I have several files with 2 php snippets nested with

<? php code code code ?> <? php code code code ?>

How can I just grab the first snippet including tags with RegEx?

Thanks!

Voldie
  • 1
  • 1

2 Answers2

3

Let's say a.php has this:

<?php code code code ?> <?php mocode mocode mocode ?>

Now we can get the first result using this answer

<?php

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

$fullstring = file_get_contents('a.php');

$tag1 = '<?php';
$tag2 = '?>';

echo $tag1.get_string_between($fullstring, $tag1, $tag2).$tag2;

It won't be visible in the regular browser window since it will be rendered as an invisible HTML tag, but the output will be visible in source as:

<?php code code code ?>

Community
  • 1
  • 1
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
  • Thanks a ton! I have been trying some differant regexs but getting no where. This is helpful. – Voldie Jun 13 '16 at 20:33
2

How about this?

$re = "/<\\?php(.+?)\\?>/i"; 
$str = "<?php some code in here ?> <?php some other code in here ?>"; 

preg_match($re, $str, $matches);
print_r($matches);

Results in this:

Array
(
    [0] => <?php some code in here ?>
    [1] =>  some code in here 
)

You also should search and try by your own please!

Community
  • 1
  • 1
Jason Schilling
  • 475
  • 6
  • 19