【问题标题】:How to replace text in regex by using "POSIX" regex如何使用“POSIX”正则表达式替换正则表达式中的文本
【发布时间】:2018-03-16 23:24:25
【问题描述】:

我在 PCRE 方法中有现有的代码,我希望在 POSIX 中具有相同的功能。 下面是我在 PCRE 中做的示例代码。

<?php

$regex = "/(\d)/";
$content = "In the garden have dog,cat,23242,rabbit.";

echo preg_replace($regex,"<span style='color:green'>$1</span>",$content);
//Result:
//In the garden have dog,cat,<span style='color:green'>2</span><span style='color:green'>3</span><span style='color:green'>2</span><span style='color:green'>4</span><span style='color:green'>2</span>,rabbit.

我正在尝试在 POXIS 中做同样的事情,但无法获得相同的输出。 下面是我在 POSIX 中做的示例代码。;

<?php

$regex = "([[:digit:]])";
$content = "In the garden have dog,cat,23242,rabbit."

echo ereg_replace($regex,"<span style='color:green'>$1</span>",$content);
//Result:
//In the garden have dog,cat,<span style='color:green'>$1</span><span style='color:green'>$1</span><span style='color:green'>$1</span><span style='color:green'>$1</span><span style='color:green'>$1</span>,rabbit.

【问题讨论】:

  • 如果preg_* 可以满足您的所有需求,为什么还需要ereg?好吧,要使ereg 函数工作相同,只需将替换字符串中的$1 替换为\\1
  • 我使用的集成系统是只读的posix。感谢您的回答,正在工作。
  • POSIX 模式(所有 ereg_* 函数)自 php 5.3 起已弃用。请不要使用它们。它们已从 php 7.0 中完全删除
  • 您可以将posix 与preg_replace 一起使用,您也可以使用量词并一次替换所有数字,还是一次替换一个? 3v4l.org/l069J 没有量词你会得到多个跨度。

标签: php regex posix-ere ereg-replace


【解决方案1】:

注意ereg_replace

这个函数在 PHP 5.3.0 中被弃用,在 PHP 7.0.0 中被移除。

如果您的 PHP 环境不支持 preg_replace,请在替换模式中使用带有 \\1 而不是 $1 的当前代码。

$regex = "([[:digit:]]+)";
$content = "In the garden have dog,cat,23242,rabbit.";
echo ereg_replace($regex,"<span style='color:green'>\\1</span>",$content);
// => In the garden have dog,cat,<span style='color:green'>23242</span>,rabbit.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 2014-03-29
    • 2014-03-11
    • 2012-02-12
    • 2017-10-18
    相关资源
    最近更新 更多