user6173198
user6173198

Reputation:

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

So I have a file 6647_241_file1.pdf and I need to get rid of the 6647_241_ part of the filename.

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

<?php
$string=$row[file_name];

becomes:

$string="6647_241_file1.pdf";

$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?

Upvotes: 1

Views: 133

Answers (2)

Rene M.
Rene M.

Reputation: 2690

Try this regexp /^[\d_]*/

$string="6647_241_file1.pdf";

$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.

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 79014

There are regexes and explodes, etc. But here's one fun way:

$result = ltrim($string, '0123456789_');

Use trim() if you want to trim both ends.

Upvotes: 1

Related Questions