php 如何使用 preg_replace 从某个字符中删除任何内容,直到字符串的结尾?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4561468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use preg_replace to remove anything from a certain character on until the end of a string?
提问by walter
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: 'merry'
...but nope.
......但没有。
The idea is to remove the underscore character '_'
and all characters to the its right.
这个想法是删除下划线字符'_'
和它右边的所有字符。
Thanks
谢谢
回答by Erik
The following would be much faster;
以下会更快;
$str = 'merry_christmas';
$str = substr($str, 0, strpos($str, '_'));
回答by Gumbo
The pattern /_*/
matches zero or more consecutive _
. So it will turn merry_christmas
into merrychristmas
.
模式/_*/
匹配零个或多个连续的_
。所以会merry_christmas
变成merrychristmas
.
What you need is /_.*/s
that matches a _
followed by zero or more arbitrary characters (note the smodifier):
您需要的是/_.*/s
匹配 a_
后跟零个或多个任意字符(注意s修饰符):
$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.
但正如其他人已经提到的,使用正则表达式可能不是最好的方法。还可以考虑使用基本字符串操作的其他提到的解决方案。并非所有这些都像使用上述正则表达式一样具有可读性(更重要的是:如果_
字符串中没有,它们可能会返回意外结果)。但在某些情况下它们可能会更快。
回答by Felix Kling
You don't need regular expressions at all, you could use explode
(substr
is probably better but I want to show another alternative):
您根本不需要正则表达式,您可以使用explode
(substr
可能更好,但我想展示另一种选择):
$string = array_shift(explode('_', $string));
Your expressions does not work, because it onlymatches a variable number of _
, not other characters.
您的表达式不起作用,因为它只匹配可变数量的_
,而不匹配其他字符。
回答by nonopolarity
it is "and everything after the underscore", so use
它是“以及下划线之后的所有内容”,因此请使用
$string = 'merry_christmas';
$string = preg_replace('/_.*/','',$string);
echo $string;
回答by salathe
回答by Poelinca Dorin
preg_replace('/_(.*)/','',$string);
回答by spuas
Your pattern is incorrect, should set it to '/_.*/' so:
您的模式不正确,应将其设置为 '/_.*/' 所以:
$string = preg_replace('/_.*/','',$string);
The '.' means any character, have a look reg_ex tutorial
这 '。' 表示任何字符,看看reg_ex教程