php 如何删除“-”之后的字符串中的任何内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4705167/
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 remove anything in a string after "-"?
提问by Mister Gan
This is the example of my string.
这是我的字符串的示例。
$x = "John Chio - Guy";
$y = "Kelly Chua - Woman";
I need the pattern for the reg replace.
我需要 reg 替换的模式。
$pattern = ??
$x = preg_replace($pattern, '', $x);
Thanks
谢谢
回答by Felix Kling
No need for regex. You can use explode
:
不需要正则表达式。您可以使用explode
:
$str = array_shift(explode('-', $str));
$str = substr($str, 0, strpos($str, '-'));
Maybe in combination with trim
to remove leading and trailing whitespaces.
也许结合trim
删除前导和尾随空格。
Update:As @Mark points out this will fail if the part you want to get contains a -
. It all depends on your possible input.
更新:正如@Mark 指出的那样,如果您想要获取的部分包含-
. 这一切都取决于您可能的输入。
So assuming you want to remove everything after the lastdash, you can use strrpos
, which finds the last occurrence of a substring:
因此,假设您想删除最后一个破折号之后的所有内容,您可以使用strrpos
,它会查找子字符串的最后一次出现:
$str = substr($str, 0, strrpos($str, '-'));
So you see, there is no regular expression needed ;)
所以你看,不需要正则表达式;)
回答by Mark Byers
To remove everything after the firsthyphen you can use this regular expression in your code:
要删除第一个连字符后的所有内容,您可以在代码中使用此正则表达式:
"/-.*$/"
To remove everything after the lasthyphen you can use this regular expression:
要删除最后一个连字符后的所有内容,您可以使用以下正则表达式:
"/-[^-]*$/"
You can also combine this with trimming whitespace from the end of the result:
您还可以将其与从结果末尾修剪空白相结合:
"/\s*-[^-]*$/"
回答by user2453885
You can also use.
您也可以使用。
strstr( "John Chio - Guy", "-", true ) . '-';
The third parameter true
tells the function to return everything before first occurrence of the second parameter.
第三个参数true
告诉函数在第二个参数第一次出现之前返回所有内容。
回答by deadlock
I hope these patterns will help you =]
我希望这些模式能帮助你 =]
$pattern1='/.+(?=\s-)/' //This will match the string before the " -";
$pattern2='/(?<=\s-\s).+/' //This will match the string after the "- ";
回答by Chris Hasiński
Explode or regexp are an overkill, try this:
Explode 或 regexp 是一种矫枉过正,试试这个:
$str = substr($str, 0, strpos($str,'-'));
$str = substr($str, 0, strpos($str,'-'));
or the strtok version in one of the answers here.
或此处答案之一中的 strtok 版本。
回答by Geoffrey K. Kamundi
Use the strstr
function.
使用该strstr
功能。
Example:
例子:
$my_string = "This is my best string - You like it?";
$my_new_string = strstr($my_string, '-', true);
echo($my_new_string);