删除除连字符&;字符串的下划线


remove all punctuation except hyphen & underscore of a string

我想删除字符串开头和结尾的所有标点符号,连字符、下划线除外。

示例:如果输入是spice-b32.lg_b32;,则使用preg_replace()后的字符串;应为:spice-b32lg_b32

我也尝试使用preg_match('/^[A-Za-z0-9]/',$inm)进行数据验证,使用$inm=preg_replace('/^'PL+|'PL'z/','',$inm);,但当输入a!-read_结果为a!-read

但输出应为:a-read

如果这个preg_replace()或preg_match()不正确,那么plz help。。

如果我能正确理解你想要什么,那么这样的东西就可以帮你了:

$inm=preg_replace('/[,.!?]*([-_]+)[,.!?]*/',
                  ''1',
                  preg_replace('/'b[.,?!]+|[.,!?]+'b/', '', $inm);

可以随意将需要剥离的其他角色添加到角色组中。

怎么样

$arr = array('spice-b32.', 'lg_b32;', 'a!-read_');
foreach ($arr as $str) {
    echo preg_replace('/^[^'P{P}_-]+|[^'P{P}_-]+$/u', '', $str),"'n";
}

这将删除字符串开头或结尾的所有标点符号(_-除外)。

输出:

spice-b32
lg_b32
a!-read_