streetparade
streetparade

Reputation: 32888

Regular Expression relace Myname _Mysurname with "" in PHP

I need a regular expression which replaces a string like this

"Myname _MySurename"  with "Myname" 

that means i just need Myname, so _MySurename should be cut.

i tryed something like "/_*/" but that replaces just the _ (underscore) how can i do that in PHP ?

Upvotes: 1

Views: 65

Answers (3)

rubber boots
rubber boots

Reputation: 15194

From your description it is obvious you
know where your string has to be splitted.
Therefore: better not use regex substitution,
but use regex split:

preg_split('/\s*_/', $text)

This returns the list of splitted entries, get the first one e.g. by:

...
$names = 'Myname_MySurename'; #  'Myname _MySurename';
# print first element of splitted array
$firstname = array_shift( preg_split('/\s*_/', $names) );
...

Regards

rbo

Upvotes: 1

codaddict
codaddict

Reputation: 455132

You can replace the underscore and the following word as:

$str = preg_replace('/_\w+/','',$str);

Looks like you also have a space after the name. So you can use:

$str = preg_replace('/\s*_\w+/','',$str);

Upvotes: 2

Turbotoast
Turbotoast

Reputation: 139

Try:

/\s_.+$/

"Replace a whitespace (the space) followed by an underscore and a number of characters". The $ makes sure that this is matched on the end of the string.

This is untested, but it should work.

Upvotes: 0

Related Questions