开发者

How to use preg_replace to remove anything from a certain character on until the end of a string?

Hi I need to remove all characters from the '_' until the end of the string.

I tried with:

$string = 'merry_christmas';

$string = preg_replace('/_*/','',$string);

echo $string; // I need it to be: '开发者_JAVA技巧merry'

...but nope.

The idea is to remove the underscore character '_' and all characters to the its right.

Thanks


The following would be much faster;

$str = 'merry_christmas';
$str = substr($str, 0, strpos($str, '_'));


The pattern /_*/ matches zero or more consecutive _. So it will turn merry_christmas into merrychristmas.

What you need is /_.*/s that matches a _ followed by zero or more arbitrary characters (note the s modifier):

$string = preg_replace('/_.*/s', '', $string);

But as the others have already mentioned, using regular expressions might not be the best way. Also consider the other mentioned solutions using basic string operations. Not all of them are as readable as using a regular expression like the one above (more important: they might return an unexpected result if there is no _ in the string). But they might be faster in certain circumstances.


You don't need regular expressions at all, you could use explode (substr is probably better but I want to show another alternative):

$string = array_shift(explode('_', $string));

Your expressions does not work, because it only matches a variable number of _, not other characters.


it is "and everything after the underscore", so use

$string = 'merry_christmas'; 
$string = preg_replace('/_.*/','',$string); 
echo $string;


Don't forget strstr(), in particular the $before_needle parameter which is available as of PHP 5.3.0.

$stub = strstr($string, '_', true) ?: $string;


preg_replace('/_(.*)/','',$string);


Your pattern is incorrect, should set it to '/_.*/' so:

$string = preg_replace('/_.*/','',$string);

The '.' means any character, have a look reg_ex tutorial

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜