PHP str_replace/preg_replace problem with php open tags
I'm trying to replace something like:
$text = "Hello <--name--> !!";
echo str_replace("--","?",$text);
Expected:
Hello <?name?> !!
Result:
Hello !!
(I'm checking the source code, and I have short open tags enabled)
I have tried so many ways but it seems that I can't never have as result any <?
(or <?php
) string.
I think it may be related to Suhosin patch that is enabled by default in Ubuntu. Before doing anything else, does someone knows how to get that 开发者_StackOverflow社区to work?
Thank you.
UPDATE:
I tried directly in command line and it worked. Yea, the problem was that anything between php tags is not displayed in the browser (Chrome), not even in the source code.
echo "A <"."?"."php"." echo 1 "." ?".">"." B";
In Chrome displays "A B" when looking at the source code. But Firefox displays it complete... So in summary Chrome was tricking me ;)
Thank you!!!
Sorry I had to choose the best answer... but for me the 3 answer were correct.
Did you really look into the source view of the browser? <? ?>
sections tend to be interpreted as tags.
If you're not using eval()
anywhere, there is no way these tags will be actually interpreted by PHP.
Maybe Suhosin filters those out but that would surprise me. You may be able to get around it by using
< >
instead.
It's got nothing to do with Suhosin.
<?name?> !!
when displayed in an HTML page results in !!
Check the page source.
I agree with Pekka and Mike (the other Mike, not me Mike) - you really need to check the HTML source code, as it will show correctly. If you really want to see the less-than and greater-than symbols in the output, you need to replace those with HTML entities (as suggested by Pekka):
$search = array('<', '>', '--');
$replace = array('<', '>', '?');
$text = 'Hello <--name--> !!';
echo str_replace($search,$replace,$text);
You could also use htmlspecialchars, like this:
$text = htmlspecialchars("Hello <--name--> !!");
echo str_replace("--","?",$text); // Hello <?name?> !!
htmlspecialchars will replace:
- & with &
- " with "
- < with <
with >
If you don't want to replace " for some reason or another it's possible (see http://se2.php.net/manual/en/function.htmlspecialchars.php). &, < and >, though, is as far as I know always replaced with &
, <
and >
when you use htmlspecialchars.
精彩评论