How to replace all symbols or spaces in a string of words with "-"
Including,? @%! $&*(whatever)
習慣沉默2017-05-16 13:18:12
$result = preg_replace('/[^w]|[_]/', '「-」', $str);
匹配替换非字母数字并替换。w
包括_
,如果想一并替换掉,再添加上 |[_]
.
Reply to comment:
If you want to replace characters other than Chinese and English, change the pattern to the following form: /[^bA-Za-zx{4e00}-x{9fa5}]/u
/[^bA-Za-zx{4e00}-x{9fa5}]/u
b 表示空格;u4e00-u9fa5
是unicode里中文的表示法,但preg_replace不支持u
的写法,可以使用 x{XXXX}
来替代;
最后使用u
b represents a space;
u4e00-u9fa5
is the representation of Chinese in unicode, but preg_replace does not support the writing method of u
, you can use x{XXXX} code> instead; 🎜Finally use the u
option to indicate that the utf-8 character set is used. 🎜reply0
迷茫2017-05-16 13:18:12
preg_replace is one method, here I provide another method, see the code below
$str = 'hello %abc?11';
$patten = array(
'【',
'】',
'「',
'?',
'%',
'&'
);
$rs = str_replace(' ','',str_replace($patten,'「-」',$str));
echo $rs;