ereg_replace 与 preg_replace

发布于 01-08 02:39 字数 239 浏览 4 评论 0原文

<?php
$string = '\n \n \n \n';
$patterns = '/\n/';
$replacements = '/\\n/';
echo preg_replace($patterns, $replacements, $string);
?>

这段代码似乎不起作用,关于为什么会发生这种情况的任何建议。它根本不回显任何内容。我可以让它与 ereg 一起工作,但想改用 preg。

<?php
$string = '\n \n \n \n';
$patterns = '/\n/';
$replacements = '/\\n/';
echo preg_replace($patterns, $replacements, $string);
?>

This segment of code does not seem to work, Any suggestions on why this is happening. It does not echo anything at all. I can get it working with ereg but wanted to change over to preg.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

離殇2025-01-15 02:39:34

PHP 文档:从 PHP 5.3.0 开始,ereg 已被弃用。强烈建议不要依赖此功能。

无论如何,您的 $patterns 没有正确转义。您需要四个 \ - 见下文:

<?php
$string = '\n \n \n \n';
$patterns = '/\\\\n/';
$replacements = '/\\n/';
echo preg_replace($patterns, $replacements, $string); // string(19) "/\n/ /\n/ /\n/ /\n/"
?>

PHP Docs: ereg has been DEPRECATED as of PHP 5.3.0. Relying on this feature is highly discouraged.

Anyways, your $patterns isn't escaped properly. You need four \'s - see below:

<?php
$string = '\n \n \n \n';
$patterns = '/\\\\n/';
$replacements = '/\\n/';
echo preg_replace($patterns, $replacements, $string); // string(19) "/\n/ /\n/ /\n/ /\n/"
?>
笔芯2025-01-15 02:39:34

这里有很多问题...

  • 您是否尝试创建一个由换行符组成的字符串? '\n \n \n \n' 不是这样的,它不起作用。使用“\n \n \n \n”并阅读有关字符串的PHP官方手册此处

  • 您的模式未正确转义。尝试 '/\\n/',无论如何,我不确定您的版本是否不起作用。

  • 更换 '/\\n/' 的原因是什么? 请提供输入字符串和所需输出的示例。

如果您尝试转义字符串以将其保存在数据库中,那么您完全走错了路。 Google 搜索 php 数据库转义,并阅读mysql_escape_string()(如果您不使用 MySQL,则为等效函数)。有一些函数可以做到这一点,并且您必须使用它们。您不能依赖(或者没有理由这样做)使用正则表达式的自定义函数。

Many issues here...

  • Are you trying to create a string made of new-line characters? '\n \n \n \n' is not the way, it does not works. Use "\n \n \n \n" and read the PHP official manual about strings here.

  • Your pattern is not escaped correctly. Try '/\\n/', anyway I'm not sure your version does not work.

  • What's the reason for your '/\\n/' replacement? Please provide an example of input string and desired output.

If you are trying to escape strings to save them in a database, you are completely on the wrong way. Google for php database escaping, and read about mysql_escape_string() (or equivalent ones if you are not using MySQL). There are functions to do it, and you have to use them. You cannot rely (or there is no reason to do it) on custom made functions using regular expressions.

故事↓在人2025-01-15 02:39:34

如果您的意思是 \n 是换行符,则不能使用单引号 ('),而应使用双引号 (")

If you mean for \n to be a new line character, you may not use single quotes ('), use double quotes (") instead

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文