猿问

从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"


慕容708150
浏览 173回答 1
1回答

千万里不及你

不需要正则表达式:<?php$arr = [&nbsp; &nbsp; 'my:command --no-question --dry-run=false',&nbsp; &nbsp; 'another:command create somefile',&nbsp; &nbsp; 'third-command --simulate=true'];foreach( $arr as $command ){&nbsp; &nbsp; echo str_replace( ' ', '_', trim( explode( '--', $command )[ 0 ] ) ).PHP_EOL;}输出:my:commandanother:command_create_somefilethird-command
随时随地看视频慕课网APP
我要回答