1

I want to be able to remove all non php data from a string / file.

Now this preg_replace line works perfectly:

preg_replace('/\?>.*\<?/', '', $src); // Remove all non php data

BUT... problem is that it works only for the first match and not for all of the string/file...

Small tweak needed here ;)

1
  • It would be nicer to use the tokenizer where possible. Commented Dec 10, 2014 at 11:19

1 Answer 1

2

It would be simpler the other way round:

preg_match_all('~<\?.+?\?>~s', $src, $m);
$php = implode('', $m[0]);

Matching non-php blocks is much trickier, because they can also occur before the first php block and after the last one: blah <? php ?> blah.

Also note that no regex solution can handle <?'s inside php strings, as in:

<? echo "hi ?>";  ?>

You have to use tokenizer to parse this correctly.

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer ! But still I'm missing something here ? take a look : <?php $src = '<?php echo "123";?> remove me <?php echo "456"; ?> remove me <?php echo "789";?>'; $php = preg_match_all('~<\?.+?\?>~s', $src, $m); $php = implode('', $m[0]); var_dump ($m); var_dump ($php); /* I'm expecting to get : <?php echo "123";?><?php echo "456"; ?><?php echo "789";?> */ ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.