删除php中从双破折号开始的所有字符串

删除php中从双破折号开始的所有字符串,php,regex,preg-replace,substr,Php,Regex,Preg Replace,Substr,假设我有3个php变量 $var1 = 'my:command --no-question --dry-run=false'; $var2 = 'another:command create somefile'; $var3 = 'third-command --simulate=true'; 如何在不影响$var2的情况下清理包含双破折号的变量 如果我使用substr,它将从$var1和$var3中删除破折号,但$var2将变为空 >>> preg_replace('

假设我有3个php变量

 $var1 = 'my:command --no-question --dry-run=false';
 $var2 = 'another:command create somefile';
 $var3 = 'third-command --simulate=true';
如何在不影响$var2的情况下清理包含双破折号的变量

如果我使用substr,它将从$var1和$var3中删除破折号,但$var2将变为空

>>> preg_replace('/[ \=\-]/', '_', substr($var1, 0, strpos($var1, " --")))
=> "my:command"
>>> preg_replace('/[ \=\-]/', '_', substr($var2, 0, strpos($var2, " --")))
=> ""
>>> preg_replace('/[ \=\-]/', '_', substr($var3, 0, strpos($var3, " --")))
=> "third-command"

预期结果:

>>> $var1
=>  "my:command"

>>> $var2
=>  "another:command_create_somefile"

>>> $var3
=>  "third_command"


不需要正则表达式:

<?php
$arr = [
    'my:command --no-question --dry-run=false',
    'another:command create somefile',
    'third-command --simulate=true'
];

foreach( $arr as $command )
{
    echo str_replace( ' ', '_', trim( explode( '--', $command )[ 0 ] ) ).PHP_EOL;
}

preg\u replace('~\s+--.*~s',''$s)
您可以使用
strstr($var1,“--”,true)
获取
--
前面的文本。它工作得非常好。谢谢你干净的一行code@AlamHo不客气。正则表达式很棒,但有时编程语言内置的便利性更容易使用。
my:command
another:command_create_somefile
third-command