讓我們假設我有這 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"
1 回答

千萬里不及你
TA貢獻1784條經驗 獲得超9個贊
不需要正則表達式:
<?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;
}
輸出:
my:command
another:command_create_somefile
third-command
- 1 回答
- 0 關注
- 186 瀏覽
添加回答
舉報
0/150
提交
取消