PHP中的正则表达式:如何替换字母数字字符之间的连字符


Regex in PHP: how do I replace hyphens between alphanumeric characters?

我试图找到并然后用en和em宽度替换连字符的实例。

因此,在示例:"10-100"中,连字符将被en宽度替换。同样,在示例中:"It is - without doubt - the worst"或:"It is - without doubt - the worst"这两个实例都将被em width替换。

然而,我只是不能找出正确的模式preg_replace()在PHP。

"/[0-9]+('-)[0-9]+/"

…似乎在进行替换,但删除了数字。

如何让preg_replace()忽略主题两侧的模式?

你可以使用向后看和向前看:

function prettyDashes($string) {
    static $regex = array(
        '/(?<='d)-(?='d)/' => '&ndash;',  // EN-dash
        '/(?<='s)-(?='s)/' => '&mdash;',  // EM-dash
        '/(?<='w)--(?='w)/' => '&mdash;', // EM-dash
    );
    return preg_replace(array_keys($regex), array_values($regex), $string);
}
$tests = array(
    'There are 10-20 dogs in the kennel.',
    'My day was - without a doubt - the worst!',
    'My day was--without a doubt--the worst!',
);
foreach ($tests as $test) {
    echo prettyDashes($test), '<br>';
}

问题是,当替换这样的东西时,很难检测和避免误报。普通的连字符词,如"to-do",不是切线(-破折号),日期,如18-12-2014,不是范围(-破折号)。您必须对所替换的内容相当保守,如果某些内容被错误地更改了,您不应该感到惊讶。

所以,感谢@mario,答案是:

"/(?=.*?[0-9])('-)(?=.*?[0-9])/"
"/(?=.*?'w)( '- )(?=.*?'w)/"
"/(?=.*?'w)( '-- )(?=.*?'w)/"