如何在" - "之后删除字符串中的任何内容?

Mis*_*Gan 20 php regex

这是我的字符串的例子.

$x = "John Chio - Guy";
$y = "Kelly Chua - Woman";
Run Code Online (Sandbox Code Playgroud)

我需要reg替换的模式.

$pattern = ??
$x = preg_replace($pattern, '', $x); 
Run Code Online (Sandbox Code Playgroud)

谢谢

Fel*_*ing 65

不需要正则表达式.你可以使用explode:

$str = array_shift(explode('-', $str));
Run Code Online (Sandbox Code Playgroud)

substrstrpos:

$str = substr($str, 0, strpos($str, '-'));
Run Code Online (Sandbox Code Playgroud)

也许与trim删除前导和尾随空格相结合.

更新:正如@Mark指出的那样,如果您想要获得的部分包含a,则会失败-.这一切都取决于你可能的输入.

因此,假设您要删除最后一个破折号后的所有内容,您可以使用strrpos它查找子字符串的最后一个匹配项:

$str = substr($str, 0, strrpos($str, '-'));
Run Code Online (Sandbox Code Playgroud)

所以你看,没有正则表达式;)

  • 我个人更喜欢第二个使用substr作为array_shift选项的选项,它为您提供了PHP 5.3应该仅通过引用传递变量的警告。 (2认同)

Mar*_*ers 9

要删除第一个连字符后的所有内容,可以在代码中使用此正则表达式:

"/-.*$/"
Run Code Online (Sandbox Code Playgroud)

要删除最后一个连字符后的所有内容,可以使用此正则表达式:

"/-[^-]*$/"
Run Code Online (Sandbox Code Playgroud)

http://ideone.com/gbLA9

您还可以将其与结果末尾的修剪空格结合使用:

"/\s*-[^-]*$/"
Run Code Online (Sandbox Code Playgroud)


Gum*_*mbo 6

你可以使用strtok:

$x = strtok($x, '-');
Run Code Online (Sandbox Code Playgroud)


use*_*885 5

您也可以使用。

strstr( "John Chio - Guy", "-", true ) . '-';
Run Code Online (Sandbox Code Playgroud)

The third parameter true tells the function to return everything before first occurrence of the second parameter.

Source on strstr() from php.net