Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP particular regular expression

Tags:

regex

php

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

like image 436
Kamzz Avatar asked Dec 31 '25 00:12

Kamzz


1 Answers

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.

like image 59
bobble bubble Avatar answered Jan 02 '26 13:01

bobble bubble



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!