tags:

views:

39

answers:

3

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 ?

A: 

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.

Turbotoast
+2  A: 

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);
codaddict
+1  A: 

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

rubber boots