ak-SE ak-SE - 5 years ago 196
PHP Question

How to convert a specific word followed by digits to subscript in a string using PHP?

How to convert a specific word followed by digits to subscript in a string using PHP?

For example,

$nutrients = "Vitamin A, Vitamin B1, Vitamin B12, 1-Octamine, 1,2,Hydroxyethyl";


The string should be converted as:

Vitamin A, Vitamin B<sub>1</sub>, Vitamin B<sub>12</sub>, 1-Octamine, 1,2,Hydroxyethyl


(Vitamin A, Vitamin B1, Vitamin B12, 1-Octamine, 1,2,Hydroxyethyl)

Pattern must match as Vitamin B<any digits>

Answer Source

This should subscript any number after Vitamin A-Z.

$nutrients = preg_replace('~(Vitamin [A-Z])(\d+)~', '$1<sub>$2</sub>', $nutrients);

The character class might not be needed, is vitamin B the only one that can have subscripts?

Regex101 demo: https://regex101.com/r/rR4nN5/1
PHP Demo: https://eval.in/518553

The + quantifier requires the preceding character be present, the * does not.

e.g.

Test\d*

matches both:

Test

and

Test123
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download