I want to remove the first occurrence of <?
and the last occurrence of ?>
from a string using preg_replace, but no matter how I attempt to escape them, they always cause trouble.
PHP Code
$string = preg_replace('/<?/', '', $string);
$string = preg_replace('/?>/', '', $string);
What shall I write into the expression area?
You can use:
$string = preg_replace('/^((?:(?!<\?).)*)<\?|\?>(?!.*?\?>)/s', '$1', $string);
Or quite simply:
$string = preg_replace('/<\?(.*)\?>/s', '$1', $string);
PS: Note that you can do this without using regex also. Use strpos
and strrpos
functions in PHP to get first position of <?
and last position of ?>
and then use substr
function.
You can use this:
$str = preg_replace('~<\?(.*)\?>~s', '$1', $str);
But if you are running an old php version that may interpret ?>
as an end tag. you can use this trick:
$str = preg_replace('~<\?(.*)\?'.'>~s', '$1', $str);