这是我的字符串的例子.
$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)
$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)
所以你看,没有正则表达式;)
要删除第一个连字符后的所有内容,可以在代码中使用此正则表达式:
"/-.*$/"
Run Code Online (Sandbox Code Playgroud)
要删除最后一个连字符后的所有内容,可以使用此正则表达式:
"/-[^-]*$/"
Run Code Online (Sandbox Code Playgroud)
您还可以将其与结果末尾的修剪空格结合使用:
"/\s*-[^-]*$/"
Run Code Online (Sandbox Code Playgroud)
您也可以使用。
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