PHP regexp-删除所有前导、尾随和独立连字符

PHP regexp-删除所有前导、尾随和独立连字符,php,regex,preg-replace,Php,Regex,Preg Replace,我正在尝试从字符串中删除所有前导、尾随和独立连字符: -on-line - auction- website 预期结果: on-line auction website 我想出了一个有效的解决方案: ^-|(?<=\s)-|-(?=\s)|-$ ^-|(?没有理由在一个正则表达式中完成所有操作。将其拆分为两个或三个 s/^-\s*//; # Strip leading hyphens and optional space s/\s*-$//; # Strip traili

我正在尝试从字符串中删除所有前导、尾随和独立连字符:

-on-line - auction- website
预期结果:

on-line auction website
我想出了一个有效的解决方案

^-|(?<=\s)-|-(?=\s)|-$

^-|(?没有理由在一个正则表达式中完成所有操作。将其拆分为两个或三个

s/^-\s*//;    # Strip leading hyphens and optional space
s/\s*-$//;    # Strip trailing hyphens and optional space
s/\s+-\s+/ /; # Change any space-hyphen-space sequences to a single space.

这就是sed/Perl语法。您将相应地调整preg_replace语法。

我想它可以缩短为:

$repl = preg_replace('/(^|\s)-|-(\s|$)/', '$1$2', $str);

您可以尝试以下操作:

-(?!\w)|(?<!\w)-
-(?!\w)|(?
这要么匹配后面跟非单词字符的破折号,要么匹配前面跟非单词字符的破折号

或者,如果您不想这样做,请匹配所有不在两个单词字符之间的破折号


您可以使用此模式:

(?<!\S)-|-(?!\S)

在PHP中,您可以使用
trim
rtrim
删除字符串开头和结尾的任何字符。然后,您可以使用
stru\u replace
从中间删除
-

$string = '-on-line - auction- website';
$string = trim($string, "-");
$string = rtrim($string,"-");
$string = str_replace("- ", " ", $string);
$string = str_replace("  ", " ", $string); //remove double spaces left by " - "
var_dump($string);
结果是:

string(24) "on-line auction website"
如果需要,可以将其堆叠成一行:

$string = $string = str_replace("  ", " ", str_replace("- ", " ", rtrim(trim($string, "-"),"-")));

这不会删除
拍卖-
中的
-
,因此OP需要准确定义“独立连字符”的含义。这里的关键点是,在单个正则表达式中尝试执行所有操作并不必要,而且实际上更容易混淆。
string(24) "on-line auction website"
$string = $string = str_replace("  ", " ", str_replace("- ", " ", rtrim(trim($string, "-"),"-")));