Search code examples
phplaravelstringintegertrim

Detect integer value inside a string, alter it and leave it in the same place within the string


Lets say we have a string that looks something like this:

10.000 some text 5.200 some text 5.290 some text

What i want to do is to remove the last zero (if it is present) from all of the present int values within the given string, the result should be:

10.00 some text 5.20 some text 5.29 some text

Is there a convenient way to do it? Strings are mostly more complicated then the example given, so I'm looking for a way to detect an integer value, check if it ends with a 0, trim that zero and leave the altered integer value at the same place inside the string.


Solution

  • $text = '10.000 some text 5.200 some text 5.290 some text';
    
    $result = preg_replace('(0(?=[^0-9.]))', '', $text);
    
    echo $result;   // Output: 10.00 some text 5.20 some text 5.29 some text
    

    Regex pattern details:

    (             Start capturing group
      0           Capturing group must start with a 0
      (?=         Start positive lookahead (meaning peek to the next character in the text)
        [^0-9.]   Make sure that the next character is not a digit or a dot
      )           End positive lookahead
    )             End capturing group