PHPLover
PHPLover

Reputation: 12957

How to get the part of string coming after first word and underscore from the given string in PHP?

Following is one variable that contains the string:

 $msg ='file_fafe9add9c26415689ffcfbc000d7751.docx';

I don't want initial part(i.e. file_) from the file name below. It should come as follows :

$msg ='fafe9add9c26415689ffcfbc000d7751.docx';

How could I achieve it in PHP in an efficient and best way?

Thanks in advance.

Upvotes: 0

Views: 148

Answers (3)

danielson317
danielson317

Reputation: 3288

You can also do it this way:

$piece = explode('_', $string, 2)[1];

This code makes one important assumption.

1.  There is at least one _ in the string

If you can safely make this assumption it's a fun snippet to use.

Upvotes: 1

n-dru
n-dru

Reputation: 9420

You can get this substring like that:

$msg ='file_fafe9add9c26415689ffcfbc000d7751.docx';
$msg = substr($msg,strpos($msg,'_')+1);
echo $msg;

Upvotes: 1

mmarques
mmarques

Reputation: 296

str_replace('file_', '', $msg)

Upvotes: 3

Related Questions