php 正则表达式仅从数字中删除破折号

php regular expression remove dashes only from digits

我正在寻找一个 reg exp 来替换包含数字的单词中的破折号 (-)

例子

string : x-y-z 1-2-3-4 should become x-y-z 1234 (x-y-z stays and 1-2-3-4 replace dashes)

string : 1-2-3-4 should become 1234

string : x-y-z should stay x-y-z

任何帮助都适用

你可以这样做

$string = preg_replace('/-/',' ',$string);

你也可以不使用正则表达式

$string = str_replace('-','',$string);

$string = strtr($string, '-', '');
preg_replace('/(?<=\d)-(?=\d)/', '', $string)

找到所有以数字开头和以数字结尾的破折号,然后将它们核对。

这对你有帮助;

<?php
$inputStr = 'x-y-z 1-2-3-4 x-y-z';

$outputStrWords = [];
$inputStrWords = explode(' ', $inputStr);
foreach ($inputStrWords as $key => $word) {
    $charactersInWord = explode('-', $word);
    $allCharsDigit = true;
    foreach ($charactersInWord as $char) {
        $allCharsDigit &= is_numeric($char) ? true : false;
    }

    $outputStrWords[$key] = $word;
    if($allCharsDigit) {
        $outputStrWords[$key] = str_replace('-', '', $word);
    }
}

$outputStr = implode(' ', $outputStrWords);

echo $outputStr; exit;

试试这个:

$x = preg_replace('/(?=(^|\s)\d+)-|-(?=\d+(\s|))/', '', 'x-y-z 1-2-3-4');