1

I have existing code doing in PCRE method and I would like to have same function in POSIX. Below is my example code did in 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.

I'm trying doing the samething in POXIS but unable to get the same output. Below is my example code did in 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.
Deno
  • 434
  • 4
  • 16
  • 1
    Why do you need `ereg` if you can do all you need with `preg_*`? Well, to make the `ereg` function work the same, just replace `$1` with `\\1` in the replacement string. – Wiktor Stribiżew Oct 05 '17 at 10:57
  • A integrate system I using is only read posix. Thank for your answer, is work. – Deno Oct 05 '17 at 10:59
  • 1
    POSIX mode (all ereg_* functions) are deprecated since php 5.3. Please don't use them. They are completely removed from php 7.0 – Xyz Oct 05 '17 at 10:59
  • You can use posix with `preg_replace`, you also can use a quantifier and replace all the numbers at once, or do you mean to replace them one at a time? https://3v4l.org/l069J without the quantifier you get multiple spans. – chris85 Oct 05 '17 at 11:01

1 Answers1

1

Note that ereg_replace,

This function was DEPRECATED in PHP 5.3.0, and REMOVED in PHP 7.0.0.

If your PHP environemnt does not support preg_replace, use the current code with \\1 instead of $1 in the replacement pattern.

$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.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563