Chris
Chris

Reputation: 33

Remove everything after last numeric value

I am trying to come up with a function that removes everything after the last numeric value of a string in PHP.

  1. String example 1:

    input: "test test 12C"
    output: "test test 12"
    
  2. String example 2:

    input: "test dddd 3323fff new 83dds"
    output: "test dddd 3323fff new 83"
    

How can I do this PHP?

I've tried the following code, but it doesn't work and I'm not that good with regex:

$address = preg_replace('/[0-9]+$/', '', $row['address']);

Upvotes: 0

Views: 669

Answers (2)

ChristianF
ChristianF

Reputation: 2061

This can be done quite nicely with a regular expression. Only with a minor adjustment to the wording of the question, namely that you want to "save everything up to and including" the last numeric value.
In that case, the RegEx becomes:

$regexp = "/^(.*\\d)\\D∕";

This binds the RegEx to the start (^), then matches everything (.*), up to the last digit (\d) which is followed by a non-digit (\D). The parantheses around a part of the pattern tells the RegEx engine that you want to save everything in between them. This is called a "capturing sub group".

Check out the PHP manual for preg_match() for more information on how to utilize that regular expression.

Upvotes: 0

davidgiga1993
davidgiga1993

Reputation: 2853

You can do this with regular rexpressions:

.*[0-9]

.* matches any character (including none)

[0-9] matches any numberic character

So you're telling regex to match a string that starts with any characters followed by a numeric character.

<?php                                                                       
  $str = 'test dddd 3323fff new 83dds';
  preg_match('/.*[0-9]/', $str, $result);
  print_r($result[0]);
?>

Upvotes: 2

Related Questions