简体   繁体   中英

PHP particular regular expression

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM