Sol Sol - 8 months ago 28
PHP Question

How can you trim numbers and underscores out of a string?

So I have a file

and I need to get rid of the
part of the filename.

My original name comes from a row, but I created what I was doing below in a simple way.




$string1 = preg_replace("/*._/", "", $string);
echo $string1;

I was just trying this but haven't been successful at it. The numbers change, so I wasn't sure of a universal way to remove them?


Try this regexp /^[\d_]*/


$string1 = preg_replace("/^[\d_]*/", "", $string);
echo $string1; 

Should echo: file1.pdf

What does it do:

  1. ^ means look at the begining of the string
  2. [] means group a couple of characters or characterclasses together as one
  3. \d is the character class for digits which are numbers
  4. _ is what it is the character himself
  5. * means the group [] can accour zero or more times

In one sentence: Select all numbers and underscores from the beginning till something else comes.