replace substring if follows number, eg screen resolution, php

时间:2015-08-07 02:03:51

标签: php regex numbers resolutions

I have looked everywhere but I am stuck and need some help.
I believe I need a regex to replace a quote " (for inches) at the end of a number.
For example 21.5" with 21.5inch
I need to do it only if the " has a number before it. Thanks in advance!

3 个答案:

答案 0 :(得分:1)

The regex for this task is

(\d)"

Here is DEMO with explanation

答案 1 :(得分:0)

Try this:

(?<=\d)"

https://regex101.com/r/lC9tZ7/2

It should grab the " as long as it follows a digit.

If it can have spaces between the digit and ", try this:

(?<=\d)\s*"

https://regex101.com/r/cT1bF7/3

答案 2 :(得分:0)

Try (\d+\.{0,1}\d+)\s*"

Explanation: Lets try matching 21.54 inch

  1. \d+ matches 21
  2. \.{0,1} escapes decimal notation and matches if there's a . atleast 0 times (i.e., there is no decimal at all) and atmost 1 times (i.e., a number can only have at most 1 decimal). So, we have so far matched 21.
  3. \d+ matches the remaining 54. So far matched 21.54
  4. \s* forgives if there is any space followed by the number
  5. " finally ensures that the number is followed by the inch notation.

Check this demo link here.