Search code examples
phpregexposix-ereereg-replace

How to replace text in regex by using "POSIX" regex


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.

Solution

  • 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.