3

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

5
  • 2
    Try preg_replace('/\B\d+|\d+\B/','<span>$0</span>', $string ) Commented Feb 14, 2017 at 13:16
  • Another idea: '/\b\d+\b(*SKIP)(*F)|(\d+)/' that can be used in your code as is. Commented Feb 14, 2017 at 13:19
  • @WiktorStribiżew your first one won't fail properly on double-or-more digit numbers. Commented Feb 14, 2017 at 13:20
  • @SebastianProske: I know it won't work in many situations. OP requirements are not that clear since a space is also a non-numeric char. Commented Feb 14, 2017 at 13:21
  • Ok sorry i'll edit my question to be more specific Commented Feb 14, 2017 at 13:23

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

You're welcome @Kamzz! Here a PHP demo at eval.in
So, the question was about how to change the digits after an ASCII letter. '~[A-Za-z]\K\d+~' will also work.
@WiktorStribiżew I have never seen that \K before, could you please provide a reference (if possible in www.regular-expressions.info)?
@WalterTross: See SO regex documentation. Also, see the Resetting the match start section at pcre.org.
@WalterTross There's also a nice chapter on rexegg about \K if you're interested. On regular-expressions.info you can read here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.