Home > Mobile >  PHP String replace <?php $test; ?> with another string
PHP String replace <?php $test; ?> with another string

Time:10-23

I need to replace a string that contains <?php echo $test; ?> with "Hello world".

strpos($string_with_php_tags,'&lt;?php echo $test; ?&gt;') !== false) // <-- not working

$hello = str_replace('&lt;?php echo $test; ?&gt;', 'hello world', $string_with_php_tags); // not working.
    

Is this possible with PHP? I couldn't find a way to escape from this. Perhaps a regex?

Thanks Jorge.

CodePudding user response:

Try this Regex

Just some backslashes on some characters does the trick

/<\?php .*; \?>/

<?php
    $str = "<?php $test; ?>";
    $pattern = "/<\?php .*; \?>/";
    $ans = preg_replace($pattern, 'Hello world', $str);
    echo $ans;
?>

Output: image Tell me if its not working...

  • Related