Let's assume i have this 3 php variables
$var1 = 'my:command --no-question --dry-run=false';
$var2 = 'another:command create somefile';
$var3 = 'third-command --simulate=true';
How can I clean up the variable containing double dash without affecting $var2.
If i use substr, it will remove dash from $var1 and $var3 but $var2 will become empty
>>> 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"
Expected result:
>>> $var1
=> "my:command"
>>> $var2
=> "another:command_create_somefile"
>>> $var3
=> "third_command"
No need for regex:
<?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;
}
Output:
my:command
another:command_create_somefile
third-command