php - 在php中从双破折号中删除所有字符串
问题描述
假设我有这 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;
}
输出:
my:command
another:command_create_somefile
third-command
推荐阅读
- linux - Reverse sort 3rd numeric column in file
- elixir - Update Ecto Changeset Assocations
- java - 使用 JDBC 模板处理 100K 插入和更新
- python-3.x - 使用 Python-pptx,PowerPoint 有什么条件会导致 KeyError?
- mysql - 我的程序返回值时出现问题
- python - 如何在循环中按月和日索引移动单元格值?
- vb.net - WinAppDriver - 如何在 VB.NET 中设置会话以测试经典 Windows 应用程序
- python - 如何修复“安装龙卷风本身以将 zmq 与龙卷风 IOLoop 一起使用。” Python中的警告
- scala - 如何在scala中覆盖别名类型的equals
- javascript - 导入组件的问题