开发者

php regular expression...weird behavior

开发者 https://www.devze.com 2023-01-19 14:06 出处:网络
What\'s wrong in this expression? echo preg_replace(\"/Condizioni/\",\"ciao\",\"<tr bla vla Condizioni\");

What's wrong in this expression?

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

It does not return anything...

Anyway I开发者_开发知识库t 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...


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.


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消