简体   繁体   中英

convert “, ” INTO “-” with regular expressions using PHP

I want to obtain this

dog-cat-mouse

From each one of those

  • dog,cat,mouse
  • dog, cat, mouse
  • dog cat mouse

What i came up with is 2 preg_replace

$str = preg_replace('/[,\s]/', '-', $str);
$str = preg_replace('/--/', '-', $str);

works on my local server BUT does not work on production, it gives me

dog, cat, mouse -> dog--cat--mouse

which is not what I want

You need + quantifier for your [,\\s] character set.

What it changes is that it now means not "any comma or a whitespace character" but "any consecutive commas and whitespace characters"

preg_replace('/[,\s]+/', '-', $str)
preg_replace('/,\h*|\h+/', '-', $str)

使用\\ h代替\\ s

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM