让我们假设我有这 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 关注
- 172 浏览
添加回答
举报
0/150
提交
取消