Rick Joe Rick Joe - 4 months ago 12
PHP Question

get the 240x670 in a string and delete?

I have a string that I want to delete part of it:

string_string_string_240x670.bmp
string_string_string_550x450.bmp
string_string_string_250x950.bmp


I want to remove the number part
240x670
.bmp

will become:

string_string_string_.bmp
string_string_string_.bmp
string_string_string_.bmp


I tried:

$a = preg_replace('[0-9]x[0-9]', '', $a);


but no success.

Answer

Note that PHP regexes use regex delimiters, and your regex is actually parse as 0-9]x[0-9 since the paired outer [...] are treated as delimiters. Use the common /.../ or ~...~ to delimit the patterns.

Since you say the files always have bmp extension, I was going to suggest

'~_[0-9]+x[0-9]+\.bmp$~'

See the demo

Details:

  • _ - an underscore
  • [0-9]+ - 1 or more digits
  • x - an x
  • [0-9]+ - 1 or more digits
  • \. - a dot
  • bmp - a literal string bmp
  • $ - end of string.

If the extension can be any, you may also leverage pathinfo to split the path and only work on the filename:

$s = "string_string_string_240x670.bmp";
$p = pathinfo($s);
if (isset($p["filename"])) {
    echo preg_replace('~_\d+x\d+$~', '_.', $p["filename"]) . $p["extension"];
}

Here, the _\d+x\d+$ does not care what extension you have, it just replaces the last _+digits+x+digits at the end of the string (filename).

See the PHP demo

Comments