Search code examples
phppreg-replaceereg-replace

Using ereg_replace or preg_replace to leave part of a filename in php


I am trying to leave only the prefix (WST in the example below) and the number. Any suffix and file extension should be removed. This should leave me with the product code in tact.

Here are three possible values:

39159 FLAN.jpg
22201-HAV.jpg
WST 503.jpg

The output I need for these three examples is:

39159
22201
WST 503

Here is my current ereg_replace, but it also removes the prefix before the number:

$number  = ereg_replace("[^0-9]", "", $value);

Solution

  • One option is to remove anything after the last digit. This may not work as expected if you have more than one number in the name:

    preg_replace("/\D+$/", "WST 503.jpg", "");
    

    Another, probably stronger option is to capture the first number, and anything before it:

    preg_match("/^\D*\d+/", "WST 503.jpg", $matches);
    print_r($matches);  // [0] => WST 503