首页 > 解决方案 > 在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"


标签: phpregexpreg-replacesubstr

解决方案


不需要正则表达式:

<?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

推荐阅读