Rick Joe Rick Joe - 1 year ago 43
PHP Question

get the 240x670 in a string and delete?

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


I want to remove the number part

will become:


I tried:

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

but no success.

Answer Source

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


See the demo


  • _ - 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