tags:

views:

44

answers:

3

What's wrong in this expression?

echo preg_replace("/Condizioni/","ciao","<tr bla vla Condizioni");

It does not return anything...

Anyway It works when I remove "<" char...but I don't understand why...is it a special char, and if so what I i have to do to match it literally.

Thank you...

+1  A: 

How do you mean "return"?

$ php --version
PHP 5.3.2 (cli) (built: Aug  7 2010 00:04:41) 
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
$ cat test.php 
#!/usr/bin/env php
<?
echo preg_replace("/Condizioni/","ciao","<tr bla vla Condizioni");
?>
$ ./test.php 
<tr bla vla ciao

This looks correct.

What were you expecting?

Johnsyweb
+2  A: 

It work as you want (code on ideone). The only thing is that echo "<tr bla vla ciao"; in a web page will cause troubles. You have to escape your HTML chars.

htmlspecialchars() will do that for you :

echo htmlspecialchars(preg_replace("/Condizioni/","ciao","<tr bla vla Condizioni"));

It will echo &lt;tr bla vla ciao.

Colin Hebert
How foolish of me!!! Thank you soo much...
cubob
A: 

There's nothing wrong with the regex; it's just that the text with a < symbol will not display properly because the browser thinks you've opened an HTML tag.

You can prove this by doing "view source" on the browser; you should see the text as you expected it.

What you need to do is do htmlentities() on the finished text before you output it, so that the < character is escaped into an entity value that the browser can display.

Spudley
How foolish of me!!! Thank you soo much...
cubob
I'll check Colin Hebert's answer only because He was the first...I'm sorry...thank you anyway...If it would be possibile to check more than one answer I would check the your one too...
cubob
@cubob - you can only tick on answer, but you can still up-vote multiple ones if they all helped.
Spudley
I know...but I still cannot do it as I don't have 15 reputation...sorry
cubob