views:

64

answers:

4

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 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.

+2  A: 

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

&lt; &gt;

instead.

Pekka
Better answer than mine. At least you gave the HTML entities to replace with. Damn slow typing.
Mike
+1  A: 

It's got nothing to do with Suhosin.

<?name?> !! when displayed in an HTML page results in !!

Check the page source.

Mike
+1  A: 

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('&lt;', '&gt;', '?');
$text = 'Hello <--name--> !!';
echo str_replace($search,$replace,$text);
Mike
A: 

You could also use htmlspecialchars, like this:

$text = htmlspecialchars("Hello <--name--> !!");
echo str_replace("--","?",$text); // Hello &lt;?name?&gt; !!

htmlspecialchars will replace:

  • & with &amp;
  • " with &quot;
  • < with &lt;
  • > with &gt;

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 &amp;, &lt; and &gt; when you use htmlspecialchars.

matsolof