I am trying to target only digits that follows non-numeric characters in a string to add some html tags around them. For the moment i am able to do it on every digit like this :
$string = preg_replace('/(\d+)/','<sub>\1</sub>', $string );
How can i do to just target digits that follows non-numeric characters ? The goal is to format strings containing chemical formulas but not the text around it.
Actually 20% O2 in N2 becomes <sub>2</sub><sub>0</sub>% O<sub>2</sub> in N<sub>2</sub>
I would like it to be 20% O<sub>2</sub> in N<sub>2</sub> instead.
How can i do this? Is it possible?
Thank you very much for your help
How can i do to just target digits that follows non-numeric characters ?
For digits that follow letters try with a lookbehind.
(?<=[A-Za-z])\d+
See demo at regex101 (and replace with <sub>\0</sub>)
For unicode letters use \pL instead of [A-Za-z] together with u flag.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With