Question

What is the most efficient way in PHP to take matches (numbers) and replace them with strings (in isolated contexts) Isolated contexts in that groups of numbers may affect the replacement values of each other.

No correct solution

OTHER TIPS

What you're looking for is a Number to Words converter. I suggest you use one of the existing solutions instead of trying to code it up yourself. Here's one using the convert_number_to_words function from this blog:

$output = preg_replace_callback('~(\d+)~', function ($matches) {
    return convert_number_to_words($matches[1]);
}, $testString);

Output:

startz[;thirty-onemendstartz[thirty-fivemend

The output is not exactly the same as in your question, but you could easily achieve this by modifying the function according to your requirements.

That looks extremely over-complicated, but... try something like this instead:

$result = preg_replace_callback("/\d+/",function($m) {
    $ret = "";
    // if the number starts with zeroes, handle them
    if( preg_match("/^0+/",$m[0],$zeroes)) $ret .= str_repeat("zero",strlen($zeroes[0]));
    // trim leading zeroes
    $number = ltrim($m[0],"0");
    // IMPLEMENT NUMBER-TO-NAME CONVERSION HERE
    // Append result to $ret
    return $ret;
},$teststring);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top