标点符号ereg_replace preg_replace

时间:2011-08-05 22:30:30

标签: php regex replace punctuation ereg

我从旧的OsCommerce安装中获得了这段代码

    $pattern = $this->attributes['SEO_REMOVE_ALL_SPEC_CHARS'] == 'true'
                    ?   "([^[:alnum:]])+"
                    :   "([[:punct:]])+";

我想修改[:punct:]选择器,使其排除 - dash。

下一行代码是

$anchor = ereg_replace($pattern, '', strtolower($string));

删除以前找到的字符。我怎么能保留我的破折号?

谢谢,马里奥

修改

我想我明白了:

$pattern = $this->attributes['SEO_REMOVE_ALL_SPEC_CHARS'] == 'true'
                    ?   "([^[:alnum:]])+"
                    :   "([^-a-zA-Z0-9[:space:]])+";

注意:破折号必须先行。或者,对于下划线:

$pattern = $this->attributes['SEO_REMOVE_ALL_SPEC_CHARS'] == 'true'
                    ?   "([^[:alnum:]])+"
                    :   "([^a-zA-Z0-9_[:space:]])+";

我没弄明白如何使用负向前瞻:(。 干杯。马里奥

1 个答案:

答案 0 :(得分:1)

您可能需要制作自己的[characterset],而不是[:punct:]

这个看起来是正确的,但你需要验证它。

[^a-zA-Z0-9-\s]

这将取代任何非(a-z)字母,数字,空格或短划线的内容。

$pattern = $this->attributes['SEO_REMOVE_ALL_SPEC_CHARS'] == 'true'
            ?   "([^[:alnum:]])+"
            :   "[^a-zA-Z0-9-\s]+";

编辑:旧回答无效,因为ereg doesn't support lookaround

尝试这种否定的预测(?!-)

$pattern = $this->attributes['SEO_REMOVE_ALL_SPEC_CHARS'] == 'true'
                ?   "([^[:alnum:]])+"
                :   "((?!-)[[:punct:]])+";