Link to home
Start Free TrialLog in
Avatar of JiveMedia
JiveMediaFlag for Australia

asked on

Stripping Numbers & File Extension from String

Hi,

I was looking to strip all numbers/other characters and the file extension from a string using PHP probably using preg_replace?

For example, the filename stored in a variable at the moment is something like: This is File - 1.jpg

I want to chop the - 1.jpg from the string so it only shows This is File

Can someone please help?

Thanks.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Maybe you can give us a few more before-and-after examples?  The concept of test-driven development is very useful when you try to define the bounds of problems like this.  Questions like "What if the name was 'This is the 3rd file.jpg' " come up.  Would the answer be "This is the rd file?"  With more test data we can probably give you a better answer!
Avatar of JiveMedia

ASKER

Hi Ray,

Good point, after some thought it would probably be best if i stripped everything after the - 1.jpg as the name might need to contain numbers.
Avatar of Terry Woods
Is it only jpg's you want to target, or other extensions too? What about other numbers? Will there always be a dash and space before the number?
Hi Terry,

Any file extension between 2 to 4 characters, so for example, it can be .ai / .jpg / .jpeg etc.

We have given our client strict file naming conventions, so it will either always be one of the following;

1) This is a file.jpg
2) This is a file - 2.jpg (the number 2 used for example, it can be - 9.jpg etc.)

Hope this clarifies it a little more.
ASKER CERTIFIED SOLUTION
Avatar of Terry Woods
Terry Woods
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Worked awesome!!!
If the space is before the dash (or if there's no dash, then before the extension):

$mystring = preg_replace('#\s?(- \d+)?\.[a-z]{2,4}$#i', '', $mystring);

Open in new window

Now that we have a clear definition of the problem, you might find it does not require regular expressions; easier to use explode() and trim().  Just a thought.