How to replace url?

I’m sorry, I’m a beginner in php. I was given a task at work to make a script in PHP. It is necessary to replace all links with numbers in the URL with letters.

For example, replace 3nsp.com with threensp.com, replace 10dna.com with tendna.com, and so on.

How to do it? Can I write a regular expression? Is there a function in php that will replace numbers with the corresponding words?

1 Like

There are dozens of string manipulaion functions in PHP. Maybe str_replace is what you’re after.

1 Like

There is also a library that I have used which turns numeric values into words.
I don’t recall the name from the top of my head, but you may find it with a search.

1 Like

This is the one:-
https://www.php.net/manual/en/class.numberformatter.php

1 Like

The NumberFormatter class is designed for formatting numbers according to locale-specific rules (e.g., commas for thousands separators, currency symbols). It doesn’t convert numbers to words.

EDIT: My mistake, it does:

<?php
$f = new NumberFormatter("en", NumberFormatter::SPELLOUT);
echo $f->format(123456);

// output: one hundred twenty-three thousand four hundred fifty-six

// To get a valid url string you also have to replace the spaces:

$urlString = str_replace(' ', '_', $f->format(123456));
2 Likes

Here’s an efficient way to achieve your goals:

<?php

$numbers = range(0, 19);
$number_words = array_map('strval', $numbers); // Convert numbers to strings

$text = "I have 3 apples and 7 oranges.";
$replaced_text = strtr($text, array_combine($numbers, $number_words));

echo $replaced_text; // Output: I have three apples and seven oranges.

This will work for range 0 to 19 (single-word numbers)

If you have some higher numbers you’ll have to use another approach.
preg_replace_callback() should help in this case.

1 Like

It actually does, I have used it for this.
See: SPELLOUT

You code does nothing but print the same text with numerals.

1 Like

Thank you so much!

Thanks, both versions work!

Thanks everyone. I managed to rename 3nsp.com with threensp.com, replace 10dna.com with tendna.com
But 23andme.com was replaced by twenty-threeandme.com ((

There is the above comment in post #5

1 Like